﻿<%@ WebHandler Language="C#" Class="OrdersHandler" %>

using System;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using ebay.Dal;
using System.Web.SessionState;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using ebay.Model;
using System.IO;

public class OrdersHandler : IHttpHandler, IRequiresSessionState
{
    public static string Id = "";//匹配时呼叫SQL是的ID.
    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text";
        string retCode = "1";
        string retMsg = "";
        string productId = "";
        string filename = "";
        string cmd = context.Request["cmd"];
        string userId = "";
        int k3UserId = -1;     
        
        if (string.IsNullOrEmpty(cmd))
        {
            retCode = "1";
            retMsg = "指令错误";
        }
        if (context.Session["UserId"] == null || context.Session["FitemId"] == null)
        {
            retCode = "1001";
            retMsg = "您还没有登陆,或登录已超时,请重新登陆!";
            cmd = "";
        }
        else
        {
            userId = context.Session["UserId"].ToString();
            k3UserId = Convert.ToInt32(context.Session["FitemId"]);
        }
        switch (cmd)
        {

            #region 评价明细修改
            case "EvaluationDetailsModify":
                {                                       
                    string EbayUserId = context.Request["ebayUserId"];
                    string FeedBackID = context.Request["FeedBackID"];
                    string ItemID = context.Request["ItemID"];
                    string CommentTime = context.Request["CommentTime"];
                    string CommentType = context.Request["CommentType"];
                    string CommentText = context.Request["CommentText"];
                    try
                    {
                        string sqlFeedBackModify = @"update [CenterDB].[dbo].[EbayFeedBack]
                                                     set [CommentTime]=@CommentTime,[CommentType]=@CommentType,[CommentText]=@CommentText
                                                     where [EbayUserId]=@EbayUserId
                                                       and [FeedbackID]=@FeedBackID
                                                       and [ItemID]=@ItemID";
                        SqlParameter[] p = { 
                                           new SqlParameter("@CommentTime",SqlDbType.VarChar),
                                           new SqlParameter("@CommentType",SqlDbType.VarChar),
                                           new SqlParameter("@CommentText",SqlDbType.VarChar),
                                           new SqlParameter("@EbayUserId",SqlDbType.VarChar),
                                           new SqlParameter("@FeedBackID",SqlDbType.VarChar),
                                           new SqlParameter("@ItemID",SqlDbType.VarChar)
                                           };
                        p[0].Value = CommentTime;
                        p[1].Value = CommentType;
                        p[2].Value = CommentText;
                        p[3].Value = EbayUserId;
                        p[4].Value = FeedBackID;
                        p[5].Value = ItemID;                        
                        SqlHelper.ExecuteNonQuery(SqlHelper.ceterDB_Conn, CommandType.Text, sqlFeedBackModify, p);
                        retCode = "0";
                        retMsg = "修改成功！";
                    }
                    catch (Exception ex)
                    {
                        retCode = "1";
                        retMsg = ex.Message;
                    }
                  
                    
                }
                break;
            #endregion

            #region 评价明细删除
            case "EvaluationDetailsDel":
                {
                    string EbayUserId = context.Request["ebayUserId"];
                    string FeedBackID = context.Request["FeedBackID"];
                    string ItemID = context.Request["ItemID"];                   
                    try
                    {
                        string sqlFeedBackModify = @"delete
                                                     from  [CenterDB].[dbo].[EbayFeedBack]                                                     
                                                     where [EbayUserId]=@EbayUserId
                                                       and [FeedbackID]=@FeedBackID
                                                       and [ItemID]=@ItemID";
                        SqlParameter[] p = {                                           
                                           new SqlParameter("@EbayUserId",SqlDbType.VarChar),
                                           new SqlParameter("@FeedBackID",SqlDbType.VarChar),
                                           new SqlParameter("@ItemID",SqlDbType.VarChar)
                                           };                       
                        p[0].Value = EbayUserId;
                        p[1].Value = FeedBackID;
                        p[2].Value = ItemID;
                        SqlHelper.ExecuteNonQuery(SqlHelper.ceterDB_Conn, CommandType.Text, sqlFeedBackModify, p);
                        retCode = "0";
                        retMsg = "删除成功！";
                    }
                    catch (Exception ex)
                    {
                        retCode = "1";
                        retMsg = ex.Message;
                    }


                }
                break;
            #endregion

            #region 生成订单明细
            case "COrderDetail":
                {
                    string ebayUserId = context.Request["ebayUserId"];
                    string orderId = context.Request["orderId"];
                    string cmdOrderDetail = @"Insert Into [CenterDB].[dbo].CustomerResolve(EbayUserId,OrderLineItemId,ProductId,CustomerLable,Quantity,SalePrice,
                                                                            ItemCost,TransactionFees,PayFee,TheoryPostAge,ActualPostAge,PackageFee,RefundLoss,Rate,WarehouseId,Mnote,Muser,Mtime,Auser,Atime) 
                                                                 SELECT b.[EbayUserId],a.OrderLineItemId,Product.ProductId,b.CustomLable,(a.Quantity +a.SendQuantity)*l.Qty as Quantity,0 as SalePrice 
                                                                      ,0 as ItemCost,0 as TransactionFees,0 as PayFee,0 as TheoryPostAge,0 as ActualPostAge,0 as PackageFee
                                                                      ,0 as RefundLoss, 1 as Rate,isnull(m.FStockId,0) as WarehouseId,'' as Mnote,'5' as Muser,GETDATE() as Mtime,'' as Auser,'1900-1-1' as Atime
                                                                  FROM [CenterDB].[dbo].[Orders] as a
                                                                      inner join [CenterDB].[dbo].[EbaySelling] as b on a.[OrderLineItemId]=b.[OrderLineItemId] and a.EbayUserId =b.EbayUserId 
                                                                      left outer join [CenterDB].[dbo].[CustomerResolve] as c on a.[OrderLineItemId]=c.[OrderLineItemId] and a.[EbayUserId]=c.[EbayUserId]
                                                                      inner join [CenterDB].[dbo].listproduct l on  l.CustomerId = [CenterDB].dbo.ReplaceCustomLable(b.EbayUserId,b.CustomLable)
                                                                      inner join [CenterDB].[dbo].Product on Product.UserCode = l.UserCode	  
                                                                      inner join [CenterDB].[dbo].StockMapping m on Product.DeliveryWarehouseId = m.WareHouseId
                                                                  where  c.[OrderLineItemId] is null
                                                                    and a.EbayUserId = @EbayUserId
                                                                    and a.OrderId = @OrderId
                                                            ";
                    try
                    {
                        SqlParameter[] p = { 
                                           new SqlParameter("@EbayUserId",SqlDbType.VarChar),
                                           new SqlParameter("@OrderId",SqlDbType.VarChar)
                                           };
                        p[0].Value = ebayUserId;
                        p[1].Value = orderId;
                        string valo = Convert.ToString(SqlHelper.ExecuteScalar(SqlHelper.ceterDB_Conn, CommandType.Text, cmdOrderDetail, p));
                        retCode = "0";
                        retMsg = "生成订单明细完成";
                    }
                    catch
                    {
                        retCode = "1";
                        retMsg = "生成订单明细失败";
                    }
                }
                break;
            #endregion
                
            #region 发货取消
            case "CancelParcel2":
                {
                    string ebayUserId = context.Request["ebayUserId"];
                    string orderId = context.Request["orderId"];
                    string cmdPrintText = @"SELECT [EbayUserId],[OrderLineItemId],[OrderId],[printed],isnull([dispatched],'n') as [dispatched]
                                             FROM [CenterDB].[dbo].[ParcelPrint]
                                             where [EbayUserId]=@EbayUserId
	                                           and [OrderId]= @OrderId
                                               and printed<>'d'
                                            ";
                    SqlParameter[] p = { 
                                           new SqlParameter("@EbayUserId",SqlDbType.VarChar),
                                           new SqlParameter("@OrderId",SqlDbType.VarChar)
                                           };
                    p[0].Value = ebayUserId;
                    p[1].Value = orderId;
                    DataSet dsPrintText = SqlHelper.ExecuteDataSet(SqlHelper.ceterDB_Conn, CommandType.Text, cmdPrintText, p);
                    int dsPrintCount = dsPrintText.Tables[0].Rows.Count;
                    if (dsPrintCount > 0)
                    {
                        string printed = Convert.ToString(dsPrintText.Tables[0].Rows[0]["printed"]);
                        string dispatched = Convert.ToString(dsPrintText.Tables[0].Rows[0]["dispatched"]);
                        if (printed.ToLower() != "d")
                        {                             
                            string cmdUpOrder = @"update [CenterDB].[dbo].[Orders]
                                               set [OrderStatusId]='10',Mtime=getdate()
                                               where [EbayUserId]=@EbayUserId
	                                             and [OrderId]= @OrderId
                                             ";
                            string valo = Convert.ToString(SqlHelper.ExecuteScalar(SqlHelper.ceterDB_Conn, CommandType.Text, cmdUpOrder, p));

                            string cmdUpPrint = @"update [CenterDB].[dbo].[ParcelPrint]
                                               set [printed]='d'
                                               where [EbayUserId]=@EbayUserId
	                                             and [OrderId]= @OrderId
                                             ";
                            string valp = Convert.ToString(SqlHelper.ExecuteScalar(SqlHelper.ceterDB_Conn, CommandType.Text, cmdUpPrint, p));
                            retCode = "0";

                            String sqlOrderInfo = @"SELECT p.FItemId,r.Quantity AS FQty FROM Orders o,CustomerResolve r,Product p WHERE o.EbayUserId = @EbayUserId AND o.OrderId = @OrderId AND o.EbayUserId = r.EbayUserId AND o.OrderLineItemId = r.OrderLineItemId AND r.ProductId = p.ProductId";
                            
                            try
                            {
                                SqlParameter[] pOrderInfos = {
                                    new SqlParameter("@EbayUserId", SqlDbType.VarChar),
                                    new SqlParameter("@OrderId", SqlDbType.VarChar)
                                };

                                pOrderInfos[0].Value = ebayUserId;
                                pOrderInfos[1].Value = orderId;
                                DataTable tbOrderInfo = SqlHelper.ExecuteDataTable(SqlHelper.ceterDB_Conn, CommandType.Text, sqlOrderInfo, pOrderInfos);

                                SqlParameter[] pDeliveryOrders = {
                                    new SqlParameter("@tbOrders", SqlDbType.Structured),
                                    new SqlParameter("@Type", SqlDbType.Int)
                                };

                                pDeliveryOrders[0].Value = tbOrderInfo;
                                pDeliveryOrders[1].Value = 2;

                                SqlHelper.ExecuteNonQuery(SqlHelper.ceterDB_Conn, CommandType.StoredProcedure, "sp_CreateDeliveryOrder", pDeliveryOrders);
                            }
                            catch
                            {
                                retCode = "1";
                                retMsg = "发货取消失败"; 
                            }
                        }
                        else 
                        {
                            retCode = "1";
                            retMsg = "订单还未打印，不能取消发货";
                        }
                    }
                    else
                    {
                        retCode = "1";
                        retMsg = "订单还未打印，不能取消发货"; 
                    }
                    
                }
                break;
            case "CancelParcel10":
                {
                    string ebayUserId = context.Request["ebayUserId"];
                    string orderId = context.Request["orderId"];
                    string cmdStock = @"SELECT c.[ProductId],isnull(a.[FQty]-a.[SQty],0)-c.Quantity  as 剩余库存
                                          FROM [CenterDB].[dbo].[Orders] as b
	                                           inner join [CenterDB].[dbo].[CustomerResolve] as c on b.[OrderLineItemId]=c.[OrderLineItemId]
	                                           inner join [AIS2011120420456].[dbo].[t_ICItemCore] as e on e.FNumber  =c.ProductId  	
	                                           inner join [192.168.1.14,5678].[pro_req].[dbo].[pro_base] as d on e.FModel =d.产品代码  
	                                           left join [CenterDB].[dbo].[v_wfh] as a on a.[ProductId]=c.[ProductId] and a.[FStockId]=case when d.[发货仓库]='中国' then '5552' else '5559'end	    
                                         where   b.[EbayUserId]=@EbayUserId
	                                        and b.[OrderId]= @OrderId
	                                        and isnull(a.[FQty]-a.[SQty],0)-c.Quantity<0";
                    SqlParameter[] p = { 
                                           new SqlParameter("@EbayUserId",SqlDbType.VarChar),
                                           new SqlParameter("@OrderId",SqlDbType.VarChar)
                                           };
                    p[0].Value = ebayUserId;
                    p[1].Value = orderId;
                    DataSet dsStock = SqlHelper.ExecuteDataSet(SqlHelper.ceterDB_Conn, CommandType.Text, cmdStock, p);
                    int dsStockCount = dsStock.Tables[0].Rows.Count;
                    if (dsStockCount > 0)
                    {
                        retCode = "1";
                        retMsg = "订单有产品数量不足，不能改成未审核"; 
                    }
                    else
                    {
                        string cmdUpOrderS = @"update [CenterDB].[dbo].[Orders]
                                               set [OrderStatusId]='1',Mtime=getdate()
                                               where [EbayUserId]=@EbayUserId
	                                             and [OrderId]= @OrderId
                                             ";
                        string val = Convert.ToString(SqlHelper.ExecuteScalar(SqlHelper.ceterDB_Conn, CommandType.Text, cmdUpOrderS, p));
                        retCode = "0";
                    }
                }
                break;
            #endregion

            #region 检查匹配
            case "CheckMatch":
                {
//                    string sqlstrategy = @"update [CenterDB].[dbo].[Orders]
//                                            set [CenterDB].[dbo].[Orders].[SendQuantity]=a.赠送个数,[CenterDB].[dbo].[Orders].Mtime=GETDATE ()
//                                            from
//                                            (
//	                                            select distinct a.[orderlineitemid],[itemid],[Quantity],max(赠送个数) as 赠送个数
//	                                            from 
//	                                            (
//		                                            SELECT min([OrderLineItemId]) as [OrderLineItemId],a.[itemid] ,sum([Quantity]) as [Quantity],sum([SendQuantity]) as [SendQuantity]
//			                                              ,[buy_quan],[send_quan],convert(int,sum([Quantity])/[buy_quan]*[send_quan]) as 赠送个数
//			                                              ,[PostageService],[BuyerName],[AddressLine1],[AddressLine2],[City],[County],[PostalCode],[Country]      
//		                                              FROM [CenterDB].[dbo].[Orders] as a
//			                                            inner join [CenterDB].[dbo].[itemid_strategy] as b on a.ItemId =b.itemid 
//		                                              where a.MatchDate >=convert(datetime,convert(varchar(10),getdate(),23))
//			                                            and a.OrderId not like '%[_]%'
//			                                            and b.signed='启用'	
//		                                              group by a.[itemid],[PostageService],[BuyerName],[AddressLine1],[AddressLine2],[City],[County],[PostalCode],[Country],[buy_quan],[send_quan]
//	                                              )as a
//	                                              where 赠送个数>[SendQuantity]
//	                                              group by a.[OrderLineItemId],[itemid],[Quantity]
//                                             )as a
//                                             where [CenterDB].[dbo].[Orders].OrderLineItemId =a.OrderLineItemId ";
//                    string sqlckm = @"update [CenterDB].[dbo].[Orders]
//                                      set OrderStatusId =3,OrderRetentionReson =OrderRetentionReson+ ' 价格为99.99元/999.99元 ',[Mtime]=GETDATE ()
//                                      where ([SalePrice] in ('99.99','999.99')
//	                                    or TotalPrice in ('99.99','999.99'))
//	                                    and OrderStatusId =1
//                                        and OrderRetentionReson not like '%价格为99.99元/999.99元%'
//                                        ";
//                    string sqlUpForbidProd = @"update  [CenterDB].[dbo].[Orders] 
//                                                                    set [CenterDB].[dbo].[Orders].OrderStatusId =11,[CenterDB].[dbo].[Orders].[Standard]='包含禁用产品' ,[CenterDB].[dbo].[Orders].[Mtime]=GETDATE ()
//                                                                    from 
//                                                                    (
//                                                                     SELECT b.[EbayUserId],a.OrderId ,Product.ProductId
//                                                                     FROM [CenterDB].[dbo].[Orders] as a
//                                                                          inner join [CenterDB].[dbo].[EbaySelling] as b on a.[OrderLineItemId]=b.[OrderLineItemId] and a.EbayUserId =b.EbayUserId 
//                                                                          left outer join [CenterDB].[dbo].[CustomerResolve] as c on a.[OrderLineItemId]=c.[OrderLineItemId] and a.[EbayUserId]=c.[EbayUserId]
//                                                                          inner join [CenterDB].[dbo].listproduct l on  l.CustomerId = [CenterDB].dbo.ReplaceCustomLable(b.EbayUserId,b.CustomLable)
//                                                                          left join [CenterDB].[dbo].Product on Product.UserCode = l.UserCode	  
//                                                                        where  c.[OrderLineItemId] is null
//		                                                                    and a.MatchDate >=convert(datetime,convert(varchar(10),getdate(),23))
//		                                                                    and a.MatchStatusId =2 		
//		                                                                    and Product.ProductId is null
//                                                                            and a.[Standard] <>'不完全代码'
//                                                                    ) as a
//                                                                    where [CenterDB].[dbo].[Orders] .EbayUserId =a.EbayUserId 
//	                                                                    and [CenterDB].[dbo].[Orders] .OrderId =a.OrderId ";
//                    string sqlin = @"Insert Into [CenterDB].[dbo].CustomerResolve(EbayUserId,OrderLineItemId,ProductId,CustomerLable,Quantity,SalePrice,
//	                                    ItemCost,TransactionFees,PayFee,TheoryPostAge,ActualPostAge,PackageFee,RefundLoss,Rate,WarehouseId,Mnote,Muser,Mtime,Auser,Atime)
//                                    SELECT b.[EbayUserId],a.OrderLineItemId,Product.ProductId,b.CustomLable,sum((a.Quantity +a.SendQuantity)*l.Qty) as Quantity,0 as SalePrice 
//	                                      ,0 as ItemCost,0 as TransactionFees,0 as PayFee,0 as TheoryPostAge,0 as ActualPostAge,0 as PackageFee
//	                                      ,0 as RefundLoss, 1 as Rate,isnull(m.FStockId,0) as WarehouseId,'' as Mnote,'5' as Muser,GETDATE() as Mtime,'' as Auser,'1900-1-1' as Atime
//                                      FROM [CenterDB].[dbo].[Orders] as a
//	                                      inner join [CenterDB].[dbo].[EbaySelling] as b on a.[OrderLineItemId]=b.[OrderLineItemId] and a.EbayUserId =b.EbayUserId 
//	                                      left outer join [CenterDB].[dbo].[CustomerResolve] as c on a.[OrderLineItemId]=c.[OrderLineItemId] and a.[EbayUserId]=c.[EbayUserId]
//	                                      inner join [CenterDB].[dbo].listproduct l on  l.CustomerId = [CenterDB].dbo.ReplaceCustomLable(b.EbayUserId,b.CustomLable)
//	                                      inner join [CenterDB].[dbo].Product on Product.UserCode = l.UserCode	  
//	                                      inner join [CenterDB].[dbo].StockMapping m on Product.DeliveryWarehouseId = m.WareHouseId
//                                      where  c.[OrderLineItemId] is null
//	                                    and a.MatchDate >=convert(datetime,convert(varchar(10),getdate(),23))
//	                                    and a.MatchStatusId =2
//                                        and a.[Standard]<>'包含禁用产品' 
//	                                    --and (a.[Standard]='' or a.[Standard]='在系统中找不到相应的商品信息，请修正商品信息')
//	                                    --and a.OrderStatusId =1 
//                                     group by  b.[EbayUserId],a.OrderLineItemId,Product.ProductId,b.CustomLable,m.FStockId";
//                    string sqlup = @"update [CenterDB].[dbo].[Orders]
//	                                set [CenterDB].[dbo].[Orders].[Standard]=[CenterDB].[dbo].[Orders].Memo,[CenterDB].[dbo].[Orders].Mtime =GETDATE ()
//	                                from [CenterDB].[dbo].[CustomerResolve] as a
//	                                where [CenterDB].[dbo].[Orders].[OrderLineItemId] =a.OrderLineItemId 
//                                      and [CenterDB].[dbo].[Orders].Mnote<>'手工清除标准化'
//	                                  and [CenterDB].[dbo].[Orders].[Standard] ='在系统中找不到相应的商品信息，请修正商品信息'
//	                                  and [CenterDB].[dbo].[Orders].MatchDate >=convert(datetime,convert(varchar(10),getdate(),23))";
//                    string sqlCountry = @"update [CenterDB].[dbo].[Orders]
//	                                    set [CenterDB].[dbo].[Orders].[Standard]='Check Country'	                                    
//	                                    where [CenterDB].[dbo].[Orders].Country not in (select [Country] from [192.168.1.14,5678].[pro_req].[dbo].[World_Country])
//	                                      and [CenterDB].[dbo].[Orders].[PostageService] in ('UK_RoyalMailSpecialDeliveryNextDay','UK_RoyalMailInternationalSignedFor')
//	                                      and [CenterDB].[dbo].[Orders].MatchDate >=convert(datetime,convert(varchar(10),getdate(),23))
//	                                      and [CenterDB].[dbo].[Orders].[Standard]=''
//                                          and [CenterDB].[dbo].[Orders].Country<>'United Kingdom'
//                                          and [CenterDB].[dbo].[Orders].Country<>'UK'
//                                          and [CenterDB].[dbo].[Orders].Country<>'GB'
//	                                      and [CenterDB].[dbo].[Orders].Mnote<>'手工清除标准化'";
//                    string sqladdress = @"  update [CenterDB].[dbo].[Orders]
//                                                          set  OrderStatusId=3,[OrderRetentionReson]=OrderRetentionReson+' 地址有问题 '
//                                                          where (AddressLine1 ='_UAES_NULL_' or AddressLine1='' or BuyerName='' )
//		                                                        and MatchDate >=convert(datetime,convert(varchar(10),getdate(),23))
//		                                                        and Mnote<>'手工清除标准化'
//                                                                and OrderRetentionReson not like '%地址有问题%'
//                                                    ";                                                                
//                    string sqladdress2 = @"  update [CenterDB].[dbo].[Orders]
//                                                          set  OrderStatusId=3,[OrderRetentionReson]= OrderRetentionReson + ' 地址中包含BFPO '
//                                                          where (AddressLine1  like '%BFPO%'    or    AddressLine2  like '%BFPO%'     )                 
//		                                                        and MatchDate >=convert(datetime,convert(varchar(10),getdate(),23))
//		                                                        and Mnote<>'手工清除标准化'
//                                                                and OrderRetentionReson not like '%地址中包含BFPO%'
//                                                        ";
//                    string sqlcountry = @"  update [CenterDB].[dbo].[Orders]
//                                                          set  OrderStatusId=3,[OrderRetentionReson]= OrderRetentionReson + ' 国家不在国家库中 '
//                                                          where Not exists (select a.[Country],[Abbreviation] from   [192.168.1.14,5678].[pro_req].[dbo].[World_Country] as a where a.[Country]=[CenterDB].[dbo].[Orders].Country or a.[Abbreviation]=[CenterDB].[dbo].[Orders].Country)
//		                                                        and MatchDate >=convert(datetime,convert(varchar(10),getdate(),23))
//		                                                        and Mnote<>'手工清除标准化'
//                                                                and OrderRetentionReson not like '%国家不在国家库中%'
                                                        //";
//                    string sqlcountry = @"  update [CenterDB].[dbo].[Orders]
//                                                     set  OrderStatusId=3,[OrderRetentionReson]= OrderRetentionReson + ' 发货国家有问题 '
//                                                     where MatchDate >=convert(datetime,convert(varchar(10),getdate(),23))
//		                                                and(( [PostageService] in ('UK_RoyalMailFirstClassRecorded','UK_RoyalMailFirstClassStandard','UK_RoyalMailSecondClassRecorded'
//											                                                ,'UK_RoyalMailSecondClassStandard','UK_RoyalMailSpecialDeliveryNextDay')
//				                                                and Country not in ('United Kingdom','GB','UK'))
//		                                                or ([PostageService] in ('UK_RoyalMailAirmailInternational','UK_RoyalMailInternationalSignedFor')
//				                                                and Country in ('United Kingdom','GB','UK')))
//                                                        and OrderRetentionReson not like '%发货国家有问题%'
//                                                    ";
//                    string sqlNotShippedAccount = @"  update [CenterDB].[dbo].[Orders]
//                                                                          set  [CenterDB].[dbo].[Orders].OrderStatusId =4,[CenterDB].[dbo].[Orders].OrderRetentionReson ='不发货账户'
//                                                                          from  [192.168.1.14,5678].[pro_req].[dbo].[NotShippedAccount]  as b
//                                                                          where [MatchDate]>=convert(datetime,convert(varchar(10),getdate(),23))
//	                                                                        and  [CenterDB].[dbo].[Orders].UserId =b.UserId 
//	                                                                        and ISNULL(b.[Deleted],'n')='n'
//                                                                    ";
                    string sqlCheckMatch=@"exec [CenterDB].[dbo].[p_CheckMatch] ";
                    try
                    {
                        //string valstrategy = Convert.ToString(SqlHelper.ExecuteScalar(SqlHelper.ceterDB_Conn, CommandType.Text, sqlstrategy, null));
                        //string valckm = Convert.ToString(SqlHelper.ExecuteScalar(SqlHelper.ceterDB_Conn, CommandType.Text, sqlckm, null));
                        //string valUpForbidProd = Convert.ToString(SqlHelper.ExecuteScalar(SqlHelper.ceterDB_Conn, CommandType.Text, sqlUpForbidProd, null));
                        //string valin = Convert.ToString(SqlHelper.ExecuteScalar(SqlHelper.ceterDB_Conn, CommandType.Text, sqlin, null));
                        //string valup = Convert.ToString(SqlHelper.ExecuteScalar(SqlHelper.ceterDB_Conn, CommandType.Text, sqlup, null));
                        //string valCountry = Convert.ToString(SqlHelper.ExecuteScalar(SqlHelper.ceterDB_Conn, CommandType.Text, sqlCountry, null));
                        //string valaddress = Convert.ToString(SqlHelper.ExecuteScalar(SqlHelper.ceterDB_Conn, CommandType.Text, sqladdress, null));
                        //string valaddress2 = Convert.ToString(SqlHelper.ExecuteScalar(SqlHelper.ceterDB_Conn, CommandType.Text, sqladdress2, null));
                        //string valcountry = Convert.ToString(SqlHelper.ExecuteScalar(SqlHelper.ceterDB_Conn, CommandType.Text, sqlcountry, null));
                        //string valNotShippedAccount = Convert.ToString(SqlHelper.ExecuteScalar(SqlHelper.ceterDB_Conn, CommandType.Text, sqlNotShippedAccount, null));
                        string valCheckMatch = Convert.ToString(SqlHelper.ExecuteScalar(SqlHelper.ceterDB_Conn, CommandType.Text, sqlCheckMatch, null));
                        Orders o = new Orders();
                        o.CheckStock(userId, out retMsg);
                        retCode = "0";
                        retMsg = "检查完成";                        
                    }
                    catch (Exception ex)
                    {
                        Log.WriteLog(ex.Message);
                        retCode = "1";
                        retMsg = ex.Message;
                    }                       
                    
                }
                break;      
            #endregion                
            #region 订单导出
            case "ordersExpore"://订单导出
                {
                    string ebayUserId = context.Request["ebayUserId"].Trim();
                    string timeFrom = context.Request["timeFrom"];
                    string timeTo = context.Request["timeTo"];
                    string orderId = context.Request["orderId"].Trim();
                    string BuyerId = context.Request["BuyerId"].Trim(); 
                    string BuyerName = context.Request["BuyerName"].Trim();
                    string NewOrderId = context.Request["NewOrderId"].Trim();
                    string OrderStatusId = context.Request["OrderStatusId"].Trim();
                    string Standard = context.Request["Standard"] == null ? "" : context.Request["Standard"].Trim();
                    string rtype = context.Request["rtype"].Trim();
                    string itemId = context.Request["ItemId"].Trim();
                    string userCode = context.Request["userCode"].Trim();
                    string reason = context.Request["Reason"].Trim();
                    string qtype = context.Request["qtype"].Trim();
                    string resend = context.Request["resend"].Trim();
                    string memo = context.Request["memo"].Trim();
                    string ResendReason = context.Request["ResendReason"].Trim();
                    string FZR = context.Request["FZR"];
                    string DE = context.Request["DE"];

                    Report rt = new Report();
                    DataTable  table = rt.GetEbaySelling(ebayUserId, timeFrom, timeTo, orderId, BuyerId, BuyerName, NewOrderId, OrderStatusId, Standard, rtype, itemId, userCode, reason, qtype, resend, memo, ResendReason, FZR, DE);

                    int tc = table.Rows.Count;
                    if (tc > 0)
                    {
                        //DataSetToExcel.DataSetOutExcel(table, "EbaySelling");
                        ExcelHelper.DownloadAsExcel(table, "EbaySelling");
                        retCode = "0";
                        retMsg = "导出完成";
                    }
                    else
                    {
                        retCode = "1";
                        retMsg = "无数据！";
                    }
                }
                break;
            #endregion
            #region 商品替换
            case "getspthid"://获取替换商品
                {
                    bool checkParas = true;
                    string oids = context.Request["oids"];
                    oids = WebUtility.InputText(oids, 255);
                    if (string.IsNullOrEmpty(oids))
                    {
                        retCode = "1";
                        retMsg = "无订单号可处理";
                        checkParas = false;
                    }
                    string[] oid = oids.Split(new char[] { ':', ',' });
                    if (oid.Length > 10)
                    {
                        retCode = "1";
                        retMsg = "订单号过多";
                        checkParas = false;
                    }
                    if (oid.Length % 2 != 0)
                    {
                        retCode = "1";
                        retMsg = "数据不正确!";
                        checkParas = false;
                    }
                    if (checkParas)
                    {
                        string sqlWhere = "";
                        for (int i = 0; i < oid.Length; i++)
                        {
                            sqlWhere += "(EbayUserId = '" + oid[i] + "' And OrderLineItemId = '" + oid[i + 1] + "') Or";
                            i++;
                        }
                        sqlWhere = sqlWhere.Remove(sqlWhere.Length - 3);
                        string cmdText = "Select distinct(ProductId) from CustomerResolve Where " + sqlWhere;
                        try
                        {
                            DataTable table = SqlHelper.ExecuteDataTable(SqlHelper.ceterDB_Conn, CommandType.Text, cmdText, null);
                            if (table.Rows.Count == 0)
                            {
                                retCode = "1";
                                retMsg = "没有查找到可以替换的商品!";
                            }
                            else if (table.Rows.Count > 1)
                            {
                                retCode = "1";
                                retMsg = "订单中有不同商品,请重新选择!";
                            }
                            else
                            {
                                retCode = "0";
                                productId = table.Rows[0][0].ToString();
                            }

                        }
                        catch (Exception e)
                        {
                            Log.WriteLog(e.Message);
                            retCode = "1";
                            retMsg = "服务器错误!";
                        }
                    }
                }
                break;
            case "spthhuan"://商品替换
                {
                    string oids = context.Request["oids"];
                    string oq = context.Request["oq"];
                    string nq = context.Request["nq"];
                    string opid = context.Request["opid"];
                    string npid = context.Request["npid"];
                    decimal oldQuantity = 0;
                    decimal newQuantity = 0;

                    bool checkParas = true;
                    if (!decimal.TryParse(oq, out oldQuantity))
                    {
                        retCode = "1";
                        retMsg = "数量不正确";
                        checkParas = false;
                    }
                    if (!decimal.TryParse(nq, out newQuantity))
                    {
                        retCode = "1";
                        retMsg = "数量不正确";
                        checkParas = false;
                    }
                    if (checkParas)
                    {
                        oids = WebUtility.InputText(oids, 255);
                        opid = WebUtility.InputText(opid, 255);
                        npid = WebUtility.InputText(npid, 255);
                        if (string.IsNullOrEmpty(oids))
                        {
                            retCode = "1";
                            retMsg = "无订单号可处理";
                        }
                        string[] oid = oids.Split(new char[] { ':', ',' });
                        if (oid.Length > 10)
                        {
                            retCode = "1";
                            retMsg = "订单号过多";
                        }
                        if (oid.Length % 2 != 0)
                        {
                            retCode = "1";
                            retMsg = "数据不正确!";
                        }
                        Orders os = new Orders();
                        bool val = os.ProductReplace(newQuantity, oldQuantity, oid, opid, npid, userId, ref retMsg);
                        if (val)
                        {
                            retCode = "0";
                        }
                        else
                        {
                            retCode = "1";
                        }
                    }
                }
                break;
            #endregion

            #region 匹配订单
            case "matchorder":
                {
                    string matchDate = context.Request["matchdate"];
                    string matchAcc = context.Request["matchAcc"];
                    if (string.IsNullOrEmpty(matchDate))
                    {
                        retCode = "1";
                        retMsg = "匹配日期不能为空!";
                    }
                    else
                    {
                        DateTime dt = new DateTime();
                        if (DateTime.TryParse(matchDate, out dt))
                        {
                            Orders os = new Orders();
                            string msg = "";
                            try
                            {
                                if (matchAcc == "empty")
                                {
                                    os.MatchOrders(dt, userId, ref msg);
                                }
                                else {
                                    os.MatchOrders(dt, userId, matchAcc, ref msg);
                                }
                                retCode = "0";
                                retMsg = msg.Replace("\r\n", "\\r\\n");
                            }
                            catch (Exception ex)
                            {
                                retCode = "1";
                                retMsg = "匹配失败";
                                Log.WriteLog(ex.ToString());
                            }
                        }
                        else
                        {
                            retCode = "1";
                            retMsg = "匹配日期格式不正确!";

                        }
                    }
                }
                break;
            #endregion
            #region
            case "replaceaccount":
                {
                    string Pdate = context.Request["Pdate"];
                    if (string.IsNullOrEmpty(Pdate))
                    {
                        retCode = "1";
                        retMsg = "Paypal日期不能为空!";

                    }
                    else
                    {
                        DateTime dt = new DateTime();
                        if (DateTime.TryParse(Pdate, out dt))
                        {
                            Orders os = new Orders();
                            int val = os.ReplacePayPalEbayUserId(dt);
                            if (val > 0)
                            {
                                retCode = "0";
                            }
                            else
                            {
                                retCode = "1";
                                retMsg = "帐号替换失败";
                            }
                        }
                        else
                        {
                            retCode = "1";
                            retMsg = "日期格式不正确!";

                        }
                    }
                }
                break;
            #endregion
            #region 匹配订单Test
            case "matchorderTest":
                {                
                   // string matchDate = context.Request["matchdate"];
                    string matchbeginDate = context.Request["matchbegindate"];
                    string matchendDate = context.Request["matchenddate"];
                    string matchAcc = context.Request["matchAcc"];
                  
                    string type = context.Request["type"];
                    string iguid_Id = "";//查看匹配运行信息（主键ID）
                    //if (string.IsNullOrEmpty(matchDate))
                    //{
                    //    retCode = "1";
                    //    retMsg = "匹配日期不能为空!";
                    //}
                    if (string.IsNullOrEmpty(matchbeginDate) || string.IsNullOrEmpty(matchendDate))
                    {
                        retCode = "1";
                        retMsg = "匹配日期不能为空!";
                    }                      
                    else
                    {                                              
                        if (type == "1")
                        {
                            iguid_Id = Id;
                        }
                       // DateTime dt = new DateTime();
                        DateTime begindt = new DateTime();
                        DateTime enddt = new DateTime();
                        begindt = DateTime.Parse(matchbeginDate);
                        enddt = DateTime.Parse(matchendDate);
                       // if (DateTime.TryParse(matchDate, out dt))
                        if (DateTime.TryParse(matchbeginDate, out begindt) || DateTime.TryParse(matchendDate, out enddt))
                        {
                            Orders os = new Orders();
                            string message = "";
                            DataTable dtstatus = os.MatchCheckStatus(iguid_Id);//提示信息
                            if (dtstatus.Rows.Count > 0)
                            {
                                string tempmsg = "";                             
                                for (int i = 0; i < dtstatus.Rows.Count; i++)
                                {                                   
                                    tempmsg = dtstatus.Rows[i]["MESSAGE"].ToString();
                                    message += "<div>状态:" + tempmsg + "</div>";
                                }                               
                                DataRow[] dr = dtstatus.Select("OUTPUT= 'OK'");//统计已完成匹配的数。
                                if (dr.Length == dtstatus.Rows.Count)
                                {
                                    retCode = "0";
                                    retMsg = message.Replace("\r\n", "\\r\\n");
                                }
                            }
                            string msg = "";
                            try
                            {
                                if (type == "0")                               
                                {
                                    if (matchAcc == "empty")
                                    {
                                        DataTable table = SqlHelper.ExecuteDataTable(SqlHelper.ceterDB_Conn, CommandType.Text, "Select EbayUserId From EbayAccount", null);
                                        foreach (DataRow r in table.Rows)
                                        {
                                            Guid iguid_matchorder = Guid.NewGuid();
                                            iguid_Id = iguid_matchorder.ToString();
                                            string ebayUserId = r[0].ToString();
                                            Id += iguid_Id + ",";
                                           // os.MatchOrders_Symphony(iguid_Id, dt, userId, ebayUserId, ref msg);
                                            os.MatchOrders_Symphony(iguid_Id, begindt,enddt, userId, ebayUserId, ref msg);
                                        }
                                        Id = Id.Remove(Id.Length - 1);
                                    }
                                    else
                                    {
                                        Guid iguid_matchorder = Guid.NewGuid();
                                        iguid_Id = iguid_matchorder.ToString();
                                        Id = iguid_Id;
                                       // os.MatchOrders_Symphony(iguid_Id, dt, userId, matchAcc, ref msg);
                                        os.MatchOrders_Symphony(iguid_Id, begindt,enddt,userId, matchAcc, ref msg);
                                    }
                                    retCode = "2";
                                    retMsg = "start";
                                }
                                else if (type == "1" && retCode == "1")
                                {
                                    retCode = "2";
                                    retMsg = message.Replace("\r\n", "\\r\\n");//提示信息。
                                }
                                //else
                                //{
                                //    retCode = "0";
                                //    retMsg = msg.Replace("\r\n", "\\r\\n");
                                //}
                            }
                            catch (Exception ex)
                            {
                                retCode = "1";
                                retMsg = "匹配失败";
                                Log.WriteLog(ex.ToString());
                            }
                        }
                        else
                        {
                            retCode = "1";
                            retMsg = "匹配日期格式不正确!";
                        }
                    }
                }
                break;
            #endregion
                
            #region 订单作废
            case "InvalidOrder":
                {
                    bool checkParas = true;

                    string data = context.Request["data"];
                    List<OrderInfo> list = GetOrderInfoList(data);
                    if (checkParas)
                    {
                        if (list == null || list.Count == 0)
                        {
                            retCode = "1";
                            retMsg = "无效的订单";
                        }
                    }
                    
                    if (checkParas)
                    {
                        string sqlWhere = "";
                        for (int i = 0; i < list.Count; i++)
                        {
                            sqlWhere += "(Orders.EbayUserId = '" + list[i].EbayUserId + "' And Orders.OrderId = '" + list[i].OrderId + "') Or";
                        }
                        sqlWhere = sqlWhere.Remove(sqlWhere.Length - 3);
                        string cmdText = @"Select isnull(CustomerResolve.OrderLineItemId,'') as olid From Orders
                        Left Outer join CustomerResolve On Orders.EbayUserId = CustomerResolve.EbayUserId And Orders.OrderLineItemId = CustomerResolve.OrderLineItemId Where " + sqlWhere;
                        DataTable table = SqlHelper.ExecuteDataTable(SqlHelper.ceterDB_Conn, CommandType.Text, cmdText, null);
                        DataRow[] rows = table.Select("olid = ''");
                        if (rows.Length > 0)
                        {
                            retCode = "1";
                            retMsg = "有订单尚未正确解析,不能作废!";
                        }
                        else
                        {
                            Orders o = new Orders();
                            bool val = o.OrderZfei(list, userId);
                            if (val)
                            {
                                retCode = "0";
                            }
                            else
                            {
                                retCode = "1";
                                retMsg = "作废操作失败!";
                            }
                        }
                    }
                }
                break;
            #endregion

            #region 负评新增
            case "NewNegative":
                {
                    string data = context.Request["data"];
                    string[] dataSplit = data.Split('※');
                    string ebayuserid = dataSplit[0];
                    string ordersalesrecordnumber = dataSplit[1];
                    string commenttext = dataSplit[2];
                    string itemid = dataSplit[3];
                    string commenttime = dataSplit[4];
                    DateTime dt;
                    if (DateTime.TryParse(commenttime, System.Globalization.DateTimeFormatInfo.InvariantInfo, System.Globalization.DateTimeStyles.None, out dt))
                    {
                        SqlParameter[] p = { 
					   new SqlParameter("@EbayUserId",SqlDbType.VarChar),
					   new SqlParameter("@OrderSalesRecordNumber",SqlDbType.VarChar),
                       new SqlParameter("@CommentText",SqlDbType.VarChar),
					   new SqlParameter("@ItemID",SqlDbType.VarChar),
                       new SqlParameter("@CommentTime",SqlDbType.VarChar)
					   };

                        p[0].Value = ebayuserid;
                        p[1].Value = ordersalesrecordnumber;
                        p[2].Value = commenttext;
                        p[3].Value = itemid;
                        p[4].Value = Convert.ToDateTime(dt).ToString("yyyy-MM-dd");

                        string sql = @"insert into [CenterDB].[dbo].[EbayFeedBack] select top 1 o.EbayUserId,replace(replace(replace(CONVERT(varchar, getdate(), 120 ),'-',''),' ',''),':','') as FeedbackID
	                                ,o.UserId as CommentingUser,0 as CommentingUserScore,@CommentText as CommentText,@CommentTime as CommentTime,
	                                'Negative' as CommentType,@ItemID as ItemID,'Seller' as [Role],o.TransactionID,o.OrderLineItemId,o.ItemTitle,
	                                o.SalePrice as ItemPrice,'' as CurrencyId,GETDATE() as ImportDate
                                from CenterDB.dbo.Orders as o
                                where EbayUserId=@EbayUserId
	                                and OrderSalesRecordNumber=@OrderSalesRecordNumber
	                                and ItemId=@ItemID";

                        int varC = Convert.ToInt32(SqlHelper.ExecuteInt(SqlHelper.ceterDB_Conn, CommandType.Text, sql, p));

                        if (varC >= 1)
                        {
                            retCode = "0";
                        }
                        else
                        {
                            retCode = "1";
                            retMsg = "ItemID无效";
                        }
                    }
                    else
                    {
                        retCode = "1";
                        retMsg = "CommentTime无效";
                    }
                }
                break;    
            #endregion

            #region 订单合并
            case "MergeOrders":
                {
                    bool checkParas = true;
                    string cmdText1 = @"Select isnull(CustomerResolve.OrderLineItemId,'') as olid From Orders
                        Left Outer join CustomerResolve On Orders.EbayUserId = CustomerResolve.EbayUserId And Orders.OrderLineItemId = CustomerResolve.OrderLineItemId";
                    string cmdText2 = "Select Distinct EbayUserId,BuyerFullName,UserId,Warehouseid,AddressLine1,AddressLine2,OrderStatusId,MatchStatusId From Orders";

                    string data = context.Request["data"];
                    List<OrderInfo> list = GetOrderInfoList(data);
                    if (checkParas)
                    {
                        if (list == null || list.Count == 0)
                        {
                            retCode = "1";
                            retMsg = "无效的订单";
                        }
                    }
                    if (checkParas)
                    {
                        string sqlWhere = "";
                        for (int i = 0; i < list.Count; i++)
                        {
                            sqlWhere += "(Orders.EbayUserId = '" + list[i].EbayUserId + "' And Orders.OrderId = '" + list[i].OrderId + "') Or";
                            i++;
                        }
                        sqlWhere = sqlWhere.Remove(sqlWhere.Length - 3);
                        cmdText1 = cmdText1 + " Where " + sqlWhere;
                        cmdText2 = cmdText2 + " Where " + sqlWhere;

                        //验证所有订单是否都已经正确解析
                        DataTable table = SqlHelper.ExecuteDataTable(SqlHelper.ceterDB_Conn, CommandType.Text, cmdText1, null);
                        DataTable CheckTable = SqlHelper.ExecuteDataTable(SqlHelper.ceterDB_Conn, CommandType.Text, cmdText2, null);
                        DataRow[] rows = table.Select("olid = ''");
                        if (rows.Length > 0)
                        {
                            retCode = "1";
                            retMsg = "有订单尚未正确解析,不能合并!";
                        }
                        else
                        {
                            if (CheckTable.Rows.Count != 1)
                            {
                                retCode = "1";
                                retMsg = "合并条件不符合,请确认选中订单中的ebay账号、buyerfullname、buyerid、仓库（根据customlable中的仓库）、shippingadress、订单状态、匹配状态相同";
                            }
                            else
                            {
                                string Msg = "";
                                Orders os = new Orders();
                                bool val = os.MegreOrders(list, userId, ref Msg);
                                if (val)
                                {
                                    retCode = "0";
                                }
                                else
                                {
                                    retCode = "1";
                                    retMsg = Msg;

                                }
                            }
                        }
                    }
                }
                break;
            #endregion

            #region 客户退货
            case "RetrunProductStop":
                {
                    bool checkParas = true;
                    if (k3UserId == -1)
                    {
                        retCode = "1";
                        retMsg = "此用户不属于K3用户,不能操作";
                        checkParas = false;
                    }
                    if (checkParas)
                    {
                        string ebayUserId = context.Request["ebayUserId"];
                        string orderId = context.Request["orderId"];
                        if (!string.IsNullOrEmpty(ebayUserId) && !string.IsNullOrEmpty(orderId))
                        {
                            string cmdText = @"Select top 1 c.SaleDate,isnull(d.createdatetime,'1900-1-1') as createdatetime From Orders c
                            Left Outer Join PPOrder d on c.EbayUserId = d.EbayUserId And c.PayPalTransactionId = d.TransactionId
                            Where c.EbayUserId = @EbayUserId And c.OrderId = @OrderId;
                            Select distinct isnull(b.FitemId,0) as FitemId,a.Quantity,a.SalePrice,isnull(d.Currency,'GBP') as Currency,isnull(a.OrderLineItemId,'') as Lid,a.WarehouseId From Orders c
                            Left Outer Join CustomerResolve a On a.OrderLineItemId = c. OrderLineItemId And a.EbayUserId = c.EbayUserId
                            Left Outer Join Product b on a.ProductId = b.ProductId
                            Left Outer Join PPOrder d on c.EbayUserId = d.EbayUserId And c.PayPalTransactionId = d.TransactionId
                            Where c.EbayUserId = @EbayUserId And c.OrderId = @OrderId";
                            try
                            {
                                SqlParameter[] p = { 
                                           new SqlParameter("@EbayUserId",SqlDbType.VarChar),
                                           new SqlParameter("@OrderId",SqlDbType.VarChar)
                                           };
                                p[0].Value = ebayUserId;
                                p[1].Value = orderId;
                                DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.ceterDB_Conn, CommandType.Text, cmdText, p);
                                DataTable t_title = ds.Tables[0];
                                DataTable table = ds.Tables[1];
                                if (table.Select("Lid = ''").Length > 0)
                                {
                                    retCode = "1";
                                    retMsg = "订单中还有为解析的CustomLable";
                                }
                                else if (table.Select("FitemId <= 0").Length > 0)
                                {
                                    retCode = "1";
                                    retMsg = "此订单中还有商品未尽K3";
                                }
                                else
                                {
                                    DateTime saleDate = Convert.ToDateTime(t_title.Rows[0][0]);
                                    DateTime pDate = Convert.ToDateTime(t_title.Rows[0][1]);
                                    System.Collections.Generic.List<ebay.Model.CustomerResolveContext> list = new System.Collections.Generic.List<ebay.Model.CustomerResolveContext>();
                                    foreach (DataRow r in table.Rows)
                                    {
                                        ebay.Model.CustomerResolveContext m = new ebay.Model.CustomerResolveContext();
                                        m.Currency = r["Currency"].ToString();
                                        m.FItemId = Convert.ToInt32(r["FitemId"]);
                                        m.Quantity = Convert.ToInt32(r["Quantity"]);
                                        m.SalePrice = Convert.ToInt32(r["SalePrice"]);
                                        m.FstockId = Convert.ToInt32(r["WarehouseId"]);
                                        list.Add(m);
                                    }
                                    string msg = "";
                                    Orders os = new Orders();
                                    bool val = os.T_F_Order(k3UserId, ebayUserId, orderId, userId, 1, 0, saleDate, pDate, list, out msg);
                                    if (val)
                                    {
                                        retCode = "0";
                                    }
                                    else
                                    {
                                        retCode = "1";
                                        retMsg = msg == "" ? msg : "服务器错误";
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                Log.WriteLog(ex.ToString());
                                retCode = "1";
                                retMsg = "服务器错误!";
                            }
                        }
                        else
                        {
                            retCode = "1";
                            retMsg = "参数不正确";
                        }
                    }
                }
                break;
            #endregion
            #region 客户退货新
            case "RetrunProduct"://退货修改时间：2012-10-19
                {
                    bool checkParas = true;
                    if (k3UserId == -1)
                    {
                        retCode = "1";
                        retMsg = "此用户不属于K3用户,不能操作";
                        checkParas = false;
                    }
                    if (checkParas)
                    {
                        string ebayUserId = context.Request["ebayUserId"];
                        string orderId = context.Request["orderId"];
                        if (!string.IsNullOrEmpty(ebayUserId) && !string.IsNullOrEmpty(orderId))
                        {
                            string cmdText = @"Select top 1 c.SaleDate,isnull(d.createdatetime,'1900-1-1') as createdatetime From Orders c
                            Left Outer Join PPOrder d on c.EbayUserId = d.EbayUserId And c.PayPalTransactionId = d.TransactionId
                            Where c.EbayUserId = @EbayUserId And c.OrderId = @OrderId;
                             Select distinct isnull(b.FitemId,0) as FitemId,a.Quantity,c.PaymentOrRefundAmount as PaymentOrRefundAmount,k.SalePrice as SalePrice,isnull(d.Currency,'GBP') as Currency,isnull(a.OrderLineItemId,'') as Lid,a.WarehouseId From Orders c
		                        Left Outer Join CustomerResolve a On a.OrderLineItemId = c. OrderLineItemId And a.EbayUserId = c.EbayUserId
		                        Left Outer Join Product b on a.ProductId = b.ProductId		                       
		                        Left Outer Join PPOrder d on c.EbayUserId = d.EbayUserId And c.PayPalTransactionId = d.TransactionId
                                inner Join K3_Price k on k.EbayUserId=c.EbayUserId and k.OrderId =c.OrderId and k.FItemId=b.FitemId
                            Where c.EbayUserId = @EbayUserId And c.OrderId = @OrderId";
                            try
                            {
                                SqlParameter[] p = { 
                                           new SqlParameter("@EbayUserId",SqlDbType.VarChar),
                                           new SqlParameter("@OrderId",SqlDbType.VarChar)
                                           };
                                p[0].Value = ebayUserId;
                                p[1].Value = orderId;
                                DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.ceterDB_Conn, CommandType.Text, cmdText, p);
                                DataTable t_title = ds.Tables[0];
                                DataTable table = ds.Tables[1];
                                if (table.Select("Lid = ''").Length > 0)
                                {
                                    retCode = "1";
                                    retMsg = "订单中还有为解析的CustomLable";
                                }
                                else if (table.Select("FitemId <= 0").Length > 0)
                                {
                                    retCode = "1";
                                    retMsg = "此订单中还有商品未尽K3";
                                }
                                else
                                {
                                    decimal gross = decimal.Parse(table.Rows[0]["PaymentOrRefundAmount"].ToString());
                                    DateTime saleDate = Convert.ToDateTime(t_title.Rows[0][0]);
                                    DateTime pDate = Convert.ToDateTime(t_title.Rows[0][1]);
                                    System.Collections.Generic.List<ebay.Model.CustomerResolveContext> list = new System.Collections.Generic.List<ebay.Model.CustomerResolveContext>();
                                    foreach (DataRow r in table.Rows)
                                    {
                                        ebay.Model.CustomerResolveContext m = new ebay.Model.CustomerResolveContext();
                                        m.Currency = r["Currency"].ToString();
                                        m.FItemId = Convert.ToInt32(r["FitemId"]);
                                        m.Quantity = Convert.ToInt32(r["Quantity"]);
                                        //m.SalePrice = Convert.ToInt32(r["SalePrice"]);
                                        m.SalePrice = Convert.ToDouble(r["SalePrice"].ToString() == "" ? "0.00" : r["SalePrice"].ToString());
                                        m.FstockId = Convert.ToInt32(r["WarehouseId"]);
                                        list.Add(m);
                                    }
                                    string msg = "";
                                    Orders os = new Orders();
                                   // bool val = os.T_F_Order(k3UserId, ebayUserId, orderId, userId, 1, 0, saleDate, pDate, list, out msg);
                                    bool val = os.T_F_OrderTest(k3UserId, ebayUserId, orderId, gross, userId, 1, 0, saleDate, pDate, list, out msg);
                                    if (val)
                                    {
                                        retCode = "0";
                                    }
                                    else
                                    {
                                        retCode = "1";
                                        retMsg = msg == "" ? msg : "服务器错误";
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                Log.WriteLog(ex.ToString());
                                retCode = "1";
                                retMsg = "服务器错误!";
                            }
                        }
                        else
                        {
                            retCode = "1";
                            retMsg = "参数不正确";
                        }
                    }
                }
                break;
            #endregion
                
            #region 取消订单保留
            case "CancelRetentionOrder":
                {
                    bool checkParas = true;
                    string data = context.Request["data"];
                    List<OrderInfo> list = GetOrderInfoList(data);
                    if (checkParas)
                    {
                        if (list == null || list.Count == 0)
                        {
                            retCode = "1";
                            retMsg = "无效的订单";
                        }
                    }
                    if (checkParas)
                    {
                        Orders o = new Orders();
                        bool val = o.OrderBao_liu(list, userId);
                        if (val)
                        {
                            retCode = "0";
                        }
                        else
                        {
                            retCode = "1";
                            retMsg = "网络繁忙,请稍后再试";
                        }
                    }
                }
                break;
            #endregion

            #region 取消匹配
            case "CancelMatch":
                {
                    bool checkParas = true;
                    string data = context.Request["data"];
                    List<OrderInfo> list = GetOrderInfoList(data);
                    if (checkParas)
                    {
                        if (list == null || list.Count == 0)
                        {
                            retCode = "1";
                            retMsg = "无效的订单";
                        }
                    }
                    if (checkParas)
                    {
                        Orders o = new Orders();
                        bool val = o.CancelMatch(list, userId);
                        if (val)
                        {
                            retCode = "0";
                        }
                        else
                        {
                            retCode = "1";
                            retMsg = "服务器错误";
                        }
                    }
                }
                break;
            #endregion

                          
                
            #region 反审核
            case "CancelAudit"://新功能修改：2012-10-22
                {
                    bool checkParas = true;                  
                    
                    if (k3UserId == -1)
                    {
                        retCode = "1";
                        retMsg = "此用户不属于K3用户,不能操作";
                        checkParas = false;
                    }

                    if (PrintRow(context.Request["orderId"]) > 0)
                    {
                        retCode = "1";
                        retMsg = "已打印的订单无法反审核！";
                        checkParas = false;
                    }//判断订单是否已打印。
                    
                    if (checkParas)
                    {
                        string ebayUserId = context.Request["ebayUserId"];
                        string orderId = context.Request["orderId"];
                        if (!string.IsNullOrEmpty(ebayUserId) && !string.IsNullOrEmpty(orderId))
                        {
                            string cmdText = @"Select top 1 c.SaleDate,isnull(d.createdatetime,'1900-1-1') as createdatetime From Orders c
                            Left Outer Join PPOrder d on c.EbayUserId = d.EbayUserId And c.PayPalTransactionId = d.TransactionId
                            Where c.EbayUserId = @EbayUserId And c.OrderId = @OrderId;
                             Select distinct isnull(b.FitemId,0) as FitemId,a.Quantity,c.PaymentOrRefundAmount as PaymentOrRefundAmount,
                                    k.SalePrice as SalePrice,isnull(d.Currency,'GBP') as Currency,isnull(a.OrderLineItemId,'') as Lid,a.WarehouseId From Orders c
		                        Left Outer Join CustomerResolve a On a.OrderLineItemId = c. OrderLineItemId And a.EbayUserId = c.EbayUserId
		                        Left Outer Join Product b on a.ProductId = b.ProductId		                       
		                        Left Outer Join PPOrder d on c.EbayUserId = d.EbayUserId And c.PayPalTransactionId = d.TransactionId
                                inner Join K3_Price k on k.EbayUserId=c.EbayUserId and k.OrderId =c.OrderId and k.FItemId=b.FitemId
                            Where c.EbayUserId = @EbayUserId And c.OrderId = @OrderId";
                            try
                            {
                                SqlParameter[] p = { 
                                           new SqlParameter("@EbayUserId",SqlDbType.VarChar),
                                           new SqlParameter("@OrderId",SqlDbType.VarChar)
                                           };
                                p[0].Value = ebayUserId;
                                p[1].Value = orderId;
                                DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.ceterDB_Conn, CommandType.Text, cmdText, p);
                                DataTable t_title = ds.Tables[0];
                                DataTable table = ds.Tables[1];
                                if (table.Select("Lid = ''").Length > 0)
                                {
                                    retCode = "1";
                                    retMsg = "订单中还有为解析的CustomLable";
                                }
                                else if (table.Select("FitemId <= 0").Length > 0)
                                {
                                    retCode = "1";
                                    retMsg = "此订单中还有商品未尽K3";
                                }
                                else
                                {
                                    decimal gross = decimal.Parse(table.Rows[0]["PaymentOrRefundAmount"].ToString());
                                    DateTime saleDate = Convert.ToDateTime(t_title.Rows[0][0]);
                                    DateTime pDate = Convert.ToDateTime(t_title.Rows[0][1]);
                                    System.Collections.Generic.List<ebay.Model.CustomerResolveContext> list = new System.Collections.Generic.List<ebay.Model.CustomerResolveContext>();
                                    foreach (DataRow r in table.Rows)
                                    {
                                        ebay.Model.CustomerResolveContext m = new ebay.Model.CustomerResolveContext();
                                        m.Currency = r["Currency"].ToString();
                                        m.FItemId = Convert.ToInt32(r["FitemId"]);
                                        m.Quantity = Convert.ToInt32(r["Quantity"]);
                                        //m.SalePrice = Convert.ToInt32(r["SalePrice"]);
                                        m.SalePrice = Convert.ToDouble(r["SalePrice"].ToString() == "" ? "0.00" : r["SalePrice"].ToString());
                                        m.FstockId = Convert.ToInt32(r["WarehouseId"]);
                                        list.Add(m);
                                    }
                                    string msg = "";
                                    Orders os = new Orders();
                                    bool val = os.T_F_OrderTest(k3UserId, ebayUserId, orderId, gross, userId, 1, 0, saleDate, pDate, list, out msg);//退货写K3.
                                    if (val)
                                    {
                                        int val2 = os.f_shen_he(ebayUserId, orderId, userId);//反审核修改订单状态。
                                        if (val2 > 0)
                                        {
                                            retCode = "0";
                                        }
                                        else
                                        {
                                            retCode = "1";
                                            retMsg = "反审核操作失败!";
                                        }
                                    }
                                    else
                                    {
                                        retCode = "1";
                                        retMsg = msg == "" ? msg : "服务器错误";
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                Log.WriteLog(ex.ToString());
                                retCode = "1";
                                retMsg = "服务器错误!";
                            }
                        }
                        else
                        {
                            retCode = "1";
                            retMsg = "参数不正确";
                        }
                    }
                }
                break;
            #endregion                                                
            #region 反审核功能关闭
            case "CancelAuditSTop"://功能关闭2012-10-22
                {                                                            
                    bool checkParas = true;
                    string data = context.Request["data"];
                    List<OrderInfo> list = GetOrderInfoList(data);
                    if (checkParas)
                    {
                        if (list == null || list.Count == 0)
                        {
                            retCode = "1";
                            retMsg = "无效的订单";
                        }
                    }
                    if (checkParas)
                    {
                        Orders o = new Orders();
                        bool val = o.f_shen_he(list, userId);
                        if (val)
                        {
                            retCode = "0";
                        }
                        else
                        {
                            retCode = "1";
                            retMsg = "反审核操作失败!";
                        }
                    }
                }
                break;
            #endregion

            #region 判断是否已有客户退款
            case "RefundAlready":
                {
                    String eBayUserId = context.Request["EbayUserId"];
                    String orderId = context.Request["OrderId"];
                    string chkCmdText = "Select Count(OrderId) From Refund Where OrderId = @OrderId And EbayUserId = @EbayUserId and Refund.StatusId<>2";
                    try
                    {
                        SqlParameter[] p = { 
                                           new SqlParameter("@EbayUserId",SqlDbType.VarChar),
                                           new SqlParameter("@OrderId",SqlDbType.VarChar)
                                           };
                        p[0].Value = eBayUserId;
                        p[1].Value = orderId;
                        int val = (int)SqlHelper.ExecuteScalar(SqlHelper.ceterDB_Conn, CommandType.Text, chkCmdText, p);
                        if (val > 0)
                        {
                            retCode = "1";
                            retMsg = val.ToString();
                            //                                checkParas = false;                            
                        }
                        else
                        {
                            retCode = "0";                           
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.WriteLog(ex.ToString());
                        retCode = "1";
                        retMsg = "服务器错误!";                     
                    }
                    
                }
                break;
            #endregion

            #region 客户退款
            case "RefundMoney":
                {
                    String data = context.Request["data"];
                    String pdata = context.Request["pd"];
                    JToken jtoken = JsonConvert.DeserializeObject(data) as JToken;
                    List<ebay.Model.CustomerResolve> resolves = JsonConvert.DeserializeObject<List<ebay.Model.CustomerResolve>>(pdata) as List<ebay.Model.CustomerResolve>;

                    String eBayUserId = jtoken["eBayUserId"].ToString();
                    String orderId = jtoken["OrderId"].ToString();
                    String txtTotalPrice = jtoken["TotalPrice"].ToString();
                    String txtType = jtoken["Type"].ToString();
                    String txtDepartment = jtoken["Department"].ToString();
                    String txtStatus = jtoken["Status"].ToString();
                    
                    if (-1 == k3UserId)
                    {
                        retCode = "1";
                        retMsg = "此用户不属于K3用户,不能操作";
                        break;
                    }
                    

                        decimal totalPrice = 0;
                        int status = 0;
                        int type = 0;
                        int department = 0;
                        if (!decimal.TryParse(txtTotalPrice, out totalPrice))
                        {
                            retCode = "1";
                            retMsg = "退款金额格式错误!";
                            break;
                        }
                        if (!int.TryParse(txtStatus, out status))
                        {
                            retCode = "1";
                            retMsg = "投诉状态错误!";
                            break;
                        }
                        if (!int.TryParse(txtType, out type))
                        {
                            retCode = "1";
                            retMsg = "退款状态错误!";
                            break;
                        }
                        if (!int.TryParse(txtDepartment, out department))
                        {
                            retCode = "1";
                            retMsg = "部门选择错误!";
                            break;
                        }
                        if (String.IsNullOrEmpty(orderId) || String.IsNullOrEmpty(eBayUserId))
                        {
                            retCode = "1";
                            retMsg = "单号信息有误!";
                            break;
                        }

                        //string chkCmdText = "Select Count(1) From Refund Where OrderId = @OrderId And EbayUserId = @EbayUserId and Refund.StatusId<>2";
                        //try
                        //{
                        //    SqlParameter[] p = { 
                        //                   new SqlParameter("@EbayUserId",SqlDbType.VarChar),
                        //                   new SqlParameter("@OrderId",SqlDbType.VarChar)
                        //                   };
                        //    p[0].Value = eBayUserId;
                        //    p[1].Value = orderId;
                        //    int val = (int)SqlHelper.ExecuteScalar(SqlHelper.ceterDB_Conn, CommandType.Text, chkCmdText, p);
                        //    if (val > 0)
                        //    {
                        //        retCode = "1";
                        //        retMsg = "该订单已形成退款单，请先处理再进行二次退款!..";
                        //        //                                checkParas = false;
                        //        break;
                        //    }
                        //}
                        //catch (Exception ex)
                        //{
                        //    Log.WriteLog(ex.ToString());
                        //    retCode = "1";
                        //    retMsg = "服务器错误!";
                        //    //                            checkParas = false;
                        //    break;
                        //}


                        Orders o = new Orders();
                        if (o.Order_Tkuan(eBayUserId, orderId, totalPrice, type, status, department, userId, resolves))
                        {
                            retCode = "0";
                        }
                        else
                        {
                            retCode = "1";
                            retMsg = "退款操作失败!";
                        }
                        
                }
                break;
            #endregion

            #region 订单拆分
            case "SplitOrder":
                {
                    string ebayUserId = context.Request["ebayUserId"];
                    string orderId = context.Request["orderId"];
                    if (!string.IsNullOrEmpty(ebayUserId) && !string.IsNullOrEmpty(orderId))
                    {
                        string cmdText = @"Select Count(1) From CustomerResolve a Left outer Join orders b on a.OrderLineItemId = b.OrderLineItemId
                        And a.EbayUserId = b.EbayUserId Where b.EbayUserId = @EbayUserId and b.OrderId = @OrderId";

                        SqlParameter[] p = { 
                                           new SqlParameter("@EbayUserId",SqlDbType.VarChar),
                                           new SqlParameter("@OrderId",SqlDbType.VarChar)
                                           };
                        p[0].Value = ebayUserId;
                        p[1].Value = orderId;

                        try
                        {
                            int val = (int)SqlHelper.ExecuteScalar(SqlHelper.ceterDB_Conn, CommandType.Text, cmdText, p);
                            if (val <= 1)
                            {
                                retCode = "1";
                                retMsg = "没有可以拆分的商品!";
                            }
                            else
                            {
                                retCode = "0";
                            }
                        }
                        catch (Exception ex)
                        {
                            Log.WriteLog(ex.ToString());
                            retCode = "1";
                            retMsg = "服务器错误!";
                        }
                    }
                }
                break;
            #endregion
                
            #region 订单重发
            case "ddcfa":
                {
                    string pd = context.Request["pd"];
                    string data = context.Request["data"];
                    if (string.IsNullOrEmpty(pd) || string.IsNullOrEmpty(data))
                    {
                        retCode = "1";
                        retMsg = "数据错误";
                    }
                    else
                    {
                        try
                        {
                            JToken jtoken = JsonConvert.DeserializeObject(pd) as JToken;
                            List<ebay.Model.CustomerResolve> list = JsonConvert.DeserializeObject<List<ebay.Model.CustomerResolve>>(data) as List<ebay.Model.CustomerResolve>;

                            string buyerName = jtoken["buyerName"].ToString();
                            string orderId = jtoken["orderId"].ToString();
                            string ebayUserId = jtoken["ebayUserId"].ToString();
                            string addr1 = jtoken["addr1"].ToString();
                            string addr2 = jtoken["addr2"].ToString();
                            string PostageService = jtoken["PostageService"].ToString();
                            string reson = jtoken["reson"].ToString();
                            
                            //2012-7-27 添加字段
                            string city = jtoken["City"].ToString();
                            string county = jtoken["County"].ToString();
                            string postalCode = jtoken["PostalCode"].ToString();
                            string country = jtoken["Country"].ToString();
                            String type = jtoken["Type"].ToString();
                            
                            Orders o = new Orders();
                            bool val = o.ReBuilderOrder(orderId, ebayUserId, buyerName, addr1, addr2, PostageService, reson, city, county, postalCode, country, type, userId, list);
                            if (val)
                            {
                                retCode = "0";
                            }
                            else
                            {
                                retCode = "1";
                                retMsg = "重发失败";
                            }
                        }
                        catch (Exception ex)
                        {
                            Log.WriteLog(ex.ToString());
                        }
                    }
                    
                }
                break;
            #endregion

            #region 过期作废
            case "InvalidOrderOutDate":
                {
                    Orders o = new Orders();
                    try
                    {
                        o.OrderGqZf();
                        retCode = "0";
                    }
                    catch
                    {
                        retCode = "1";
                        retMsg = "服务器错误!";

                    }
                }
                break;
            #endregion

            #region 手动匹配
            case "handmatch":
                {
                    bool checkParas = true;
                    string oids = context.Request["oids"];
                    string transactionId = context.Request["transactionId"];
                    oids = WebUtility.InputText(oids, 255);
                    if (checkParas)
                    {
                        if (string.IsNullOrEmpty(oids))
                        {
                            retCode = "1";
                            retMsg = "无订单号可处理";
                            checkParas = false;
                        }
                    }
                    if (checkParas)
                    {
                        if (string.IsNullOrEmpty(transactionId))
                        {
                            retCode = "1";
                            retMsg = "没有选择PayPal订单";
                            checkParas = false;
                        }
                    }
                    string[] oid = oids.Split(new char[] { ':', ',' });
                    //if (checkParas)
                    //{
                    //    if (oid.Length > 10)
                    //    {
                    //        retCode = "1";
                    //        retMsg = "订单号过多";
                    //        checkParas = false;
                    //    }
                    //}
                    if (checkParas)
                    {
                        if (oid.Length % 2 != 0)
                        {
                            retCode = "1";
                            retMsg = "数据不正确!";
                            checkParas = false;
                        }
                    }
                    if (checkParas)
                    {
                        transactionId = WebUtility.InputText(transactionId, 30);
                        Orders o = new Orders();
                        try
                        {
                            int val = o.CheckPPStatusId(transactionId);//验证订单匹配状态
                            if (val == 1)
                            {
                                o.HandMatch(oid, userId, transactionId);
                                retCode = "0";
                            }
                            else
                            {
                                retCode = "1";
                                retMsg = "订单中包含已匹配订单"; 
                            }                            
                        }
                        catch (Exception ex)
                        {
                            Log.WriteLog(ex.ToString());
                            retCode = "1";
                            retMsg = "服务器内部错误";
                        }
                    }
                }
                break;
            #endregion

            #region 手动匹配——关联
            case "relation":
                {
                    bool checkParas = true;
                    string oid = context.Request["oid"];
                    string ebayuserid = context.Request["ebayuserid"];
                    //string orderLineItemId = context.Request["orderLineItemId"];                 
                    string tsId = context.Request["tsId"];
                    tsId = WebUtility.InputText(tsId, 80);
                    if (checkParas)
                    {
                        if (string.IsNullOrEmpty(tsId))
                        {
                            retCode = "1";
                            retMsg = "无paypal订单号可处理";
                            checkParas = false;
                        }
                    }
                    if (checkParas)
                    {
                        if (string.IsNullOrEmpty(oid))
                        {
                            retCode = "1";
                            retMsg = "没有选择Orders订单";
                            checkParas = false;
                        }
                        if (string.IsNullOrEmpty(ebayuserid))
                        {
                            retCode = "1";
                            retMsg = "没有选择Orders订单";
                            checkParas = false;
                        }
                    }
                    if (checkParas)
                    {
                        oid = WebUtility.InputText(oid, 30);

                        Orders o = new Orders();
                        try
                        {
                            o.MatchRelation(ebayuserid, oid, tsId, userId);//关联
                            retCode = "0";
                        }
                        catch (Exception ex)
                        {
                            Log.WriteLog(ex.ToString());
                            retCode = "1";
                            retMsg = "服务器内部错误";
                        }
                    }
                }
                break;
            #endregion

            #region 退款审核
            case "tkshe":
                {
                    bool checkParas = true;
                    string oids = context.Request["oids"];
                    oids = WebUtility.InputText(oids,1000);
                    if (checkParas)
                    {
                        if (string.IsNullOrEmpty(oids))
                        {
                            retCode = "1";
                            retMsg = "无订单号可处理";
                            checkParas = false;
                        }
                    }
                    string[] oid = oids.Split(new char[] { ':', ',' });                  
                    if (checkParas)
                    {
                        if (oid.Length % 3 != 0)
                        {
                            retCode = "1"; 
                            retMsg = "数据不正确!";
                            checkParas = false;
                        }
                    }                    
                    if (checkParas)
                    {
                        Orders o = new Orders();
                        try
                        {
                            o.KH_TK(oid, k3UserId, userId);
                            retCode = "0";
                        }
                        catch (Exception ex)
                        {
                            Log.WriteLog(ex.ToString());
                            retCode = "1";
                            retMsg = "服务器内部错误";
                        }
                    }
                }
                break;
            #endregion
                
            #region 获得退款金额(Gross)
            case "getppgross":
                {
                    string ebayUserId = context.Request["ebayid"];
                    string orderId = context.Request["oid"];
                    bool checkParas = true;
                    if (checkParas)
                    {
                        ebayUserId = WebUtility.InputText(ebayUserId, 80);
                        orderId = WebUtility.InputText(orderId, 80);
                        if (string.IsNullOrEmpty(ebayUserId) && string.IsNullOrEmpty(orderId))
                        {
                            retCode = "1";
                            retMsg = "无退款单可处理";
                        }
                    }
                    if (checkParas)
                    {
                        try
                        {
                            ebay.Dal.CenterDB_OrderTableAdapters.T_PPOrderTableAdapter pporder = new ebay.Dal.CenterDB_OrderTableAdapters.T_PPOrderTableAdapter();
                            DataTable dt = pporder.GetDataByOrderId(ebayUserId, orderId);
                            string price = "";
                            if (dt.Rows.Count > 0)
                            {
                                price = Convert.ToDecimal(dt.Rows[0]["Gross"]).ToString("#0.00");
                                retCode = "0";
                                retMsg = price;
                            }
                        }
                        catch (Exception ex)
                        {
                            Log.WriteLog(ex.ToString());
                            retCode = "1";
                            retMsg = "服务器内部错误";
                        }
                    }
                }
                break;
            #endregion
                
            #region 退款作废
            case "tkzfei":
                {
                    bool checkParas = true;
                    string oids = context.Request["oids"];
                    oids = WebUtility.InputText(oids, 255);
                    if (checkParas)
                    {
                        if (string.IsNullOrEmpty(oids))
                        {
                            retCode = "1";
                            retMsg = "无订单号可处理";
                            checkParas = false;
                        }
                    }                    
                    string[] oid = oids.Split(new char[] { ':', ',' });                
                    if (checkParas)
                    {
                        Orders o = new Orders();
                        try
                        {
                            o.KH_TK_Zfei(oid, userId);
                            retCode = "0";
                        }
                        catch (Exception ex)
                        {
                            Log.WriteLog(ex.ToString());
                            retCode = "1";
                            retMsg = "服务器内部错误";
                        }
                    }
                }
                break;
            #endregion

            #region 写入凭证
            case "writeVoucher":
                {
                    string Pdate = context.Request["Pdate"];
                    if (string.IsNullOrEmpty(Pdate))
                    {
                        retCode = "1";
                        retMsg = "Paypal日期不能为空!";

                    }
                    else
                    {
                        DateTime dt = new DateTime();
                        if (DateTime.TryParse(Pdate, out dt))
                        {
                            Orders os = new Orders();
                            bool val = os.WriteVoucher(dt);
                            if (val)
                            {
                                retCode = "0";
                            }
                            else
                            {
                                retCode = "1";
                                retMsg = "写入凭证失败";
                            }
                        }
                        else
                        {
                            retCode = "1";
                            retMsg = "写入凭证日期格式不正确!";

                        }
                    }
                }
                break;
            #endregion
            #region 批量修改
            case "UpdateOrders":
                {
                    string statusId = context.Request["statusId"];
                    string deliveryId = context.Request["deliveryId"];
                    string data = context.Request["data"];
                    List<OrderInfo> list = GetOrderInfoList(data);
                    bool checkParas = true;
                    int StatusId = 0;
                    int DeliveryId = 0;

                    if (checkParas)
                    {
                        if (list == null || list.Count == 0)
                        {
                            retCode = "1";
                            retMsg = "空数据!";
                            checkParas = false;
                        }
                    }
                    if (checkParas)
                    {
                        if (statusId != " ")
                        {
                            if (!int.TryParse(statusId, out StatusId))
                            {
                                retCode = "1";
                                retMsg = "订单状态错误!";
                                checkParas = false;
                            }
                        }
                    }
                    if (checkParas)
                    {
                        if (deliveryId != " ")
                        {
                            if (!int.TryParse(deliveryId, out DeliveryId))
                            {
                                retCode = "1";
                                retMsg = "发货方式错误!";
                                checkParas = false;
                            }
                        }
                    }
                    if (checkParas)
                    {
                        Orders o = new Orders();
                        try
                        {
                            o.ReviseOrders(list, StatusId, DeliveryId, userId);//批量修改
                            retCode = "0";
                        }
                        catch (Exception ex)
                        {
                            Log.WriteLog(ex.ToString());
                            retCode = "1";
                            retMsg = "服务器内部错误";
                        }
                    }
                }
                break;
            #endregion
            #region 新商品替换
            case "xinspthuan"://新商品替换
                {
                    string ebayid = context.Request["ebayid"];
                    string olineid = context.Request["olineid"];
                    string oq = context.Request["oq"];
                    string nq = context.Request["nq"];
                    string opid = context.Request["opid"];
                    string npid = context.Request["npid"];
                    decimal oldQuantity = 0;
                    decimal newQuantity = 0;
                    bool checkParas = true;
                    if (!decimal.TryParse(oq, out oldQuantity))
                    {
                        retCode = "1";
                        retMsg = "数量不正确";
                        checkParas = false;
                    }
                    if (!decimal.TryParse(nq, out newQuantity))
                    {
                        retCode = "1";
                        retMsg = "数量不正确";
                        checkParas = false;
                    }
                    if (checkParas)
                    {
                        ebayid = WebUtility.InputText(ebayid, 80);
                        olineid = WebUtility.InputText(olineid, 80);
                        opid = WebUtility.InputText(opid, 255);
                        npid = WebUtility.InputText(npid, 255);
                        if (string.IsNullOrEmpty(ebayid) && string.IsNullOrEmpty(olineid))
                        {
                            retCode = "1";
                            retMsg = "无订单号可处理";
                        }
                        Orders os = new Orders();
                        try
                        {
                            bool val = os.OrderProductReplace(newQuantity, oldQuantity, opid, npid, ebayid, olineid, userId, ref retMsg);//商品替换
                            if (val)
                            {
                                retCode = "0";
                            }
                            else
                            {
                                retCode = "1";
                            }
                        }
                        catch
                        {
                            retCode = "1";
                        }
                    }
                }
                break;
            #endregion
            #region 退款单维护——修改
            case "tkdxgai"://退款单维护——修改
                {
                    string ebayuserId = context.Request["ebayid"];
                    string refundId = context.Request["refundId"];
                    string orderId = context.Request["orderid"];
                    string tp = context.Request["tp"];
                    string did = context.Request["did"];
                    string dtype = context.Request["dtype"];
                    string dpId = context.Request["dpid"];
                    
                    string oStatusid = context.Request["oStatusid"];//退款但状态。
                    
                    decimal totalPrice = 0m;
                    int disputeId = 0;
                    int refundtype = 0;
                    int departmentId = 0;
                    bool checkParas = true;
                    if (!decimal.TryParse(tp, out totalPrice))
                    {
                        retCode = "1";
                        retMsg = "金额不正确";
                        checkParas = false;
                    }
                    if (checkParas)
                    {
                        if (!int.TryParse(did, out disputeId))
                        {
                            retCode = "1";
                            retMsg = "投诉状态错误!";
                            checkParas = false;
                        }
                    }
                    if (checkParas)
                    {
                        if (!int.TryParse(dtype, out refundtype))
                        {
                            retCode = "1";
                            retMsg = "退款类型错误!";
                            checkParas = false;
                        }
                    }
                    if (checkParas)
                    {
                        if (!int.TryParse(dpId, out departmentId))
                        {
                            retCode = "1";
                            retMsg = "部门选择错误!";
                            checkParas = false;
                        }
                    }
                    if (checkParas)
                    {
                        ebayuserId = WebUtility.InputText(ebayuserId, 80);
                        refundId = WebUtility.InputText(refundId, 30);
                        orderId = WebUtility.InputText(orderId, 80);
                        if (string.IsNullOrEmpty(ebayuserId) && string.IsNullOrEmpty(refundId))
                        {
                            retCode = "1";
                            retMsg = "无退款单可处理";
                        }
                        Orders os = new Orders();
                        try
                        {
                            bool val = false;
                            if (oStatusid == "0")
                            {
                                 val = os.RefundEditData(ebayuserId, refundId, orderId, totalPrice, disputeId, refundtype, departmentId, userId, ref retMsg);//退款单修改 
                            }
                            else
                            {
                                //二次退款 修改时间：2012-8-6-7
                                val = os.SecondRefund(ebayuserId, refundId, orderId, totalPrice, disputeId, refundtype, departmentId, userId); 
                            }
                            if (val)
                            {
                                retCode = "0";
                            }
                            else
                            {
                                retCode = "1";
                            }
                        }
                        catch
                        {
                            retCode = "1";
                        }
                    }
                }
                break;
            #endregion
            #region 退款单二次退款——获得金额
            case "tkdjine"://获得金额——修改时间：2012-8-7
                {
                    string ebayuserId = context.Request["ebayid"];
                    string refundId = context.Request["refundId"];
                    string orderId = context.Request["orderid"];
                    bool checkParas = true;
                    if (checkParas)
                    {
                        ebayuserId = WebUtility.InputText(ebayuserId, 80);
                        refundId = WebUtility.InputText(refundId, 30);
                        orderId = WebUtility.InputText(orderId, 80);
                        if (string.IsNullOrEmpty(ebayuserId) && string.IsNullOrEmpty(refundId))
                        {
                            retCode = "1";
                            retMsg = "无退款单可处理";
                        }
//                        string cmdText = @"select isnull(sum(o.TotalPrice * o.Quantity) - r.RefundAmount,0) as price from Refund r 
//                                                  left join Orders o on r.EbayUserId =o.EbayUserId and r.OrderId =o.OrderId where r.RefundId =@RefundId 
//                                                  and r.EbayUserId=@EbayUserId and r.OrderId=@OrderId group by r.RefundAmount";
                        string cmdText = @"SELECT  distinct isnull(PPOrder.Gross-Refund.RefundAmount,0) as price,PPOrder.Gross,Refund.RefundAmount
		                                            FROM PPOrder
		                                            left outer join MatchMapping ON PPOrder.TransactionId = MatchMapping.TransactionId AND PPOrder.EbayUserId = MatchMapping.EbayUserId           
		                                            Left Outer Join EbaySelling On PPOrder.EbayUserId = EbaySelling.EbayUserId And PPOrder.TransactionId = EbaySelling.PayPalTransactionId
		                                            left outer join Refund  on EbaySelling.EbayUserId =Refund.EbayUserId and EbaySelling.OrderId =Refund.OrderId       
	                                            WHERE   (Refund.RefundId=@RefundId and PPOrder.EbayUserId =@EbayUserId) AND (MatchMapping.OrderId = @OrderId Or EbaySelling.OrderId = @OrderId)";
                        SqlParameter[] p = {
                                            new SqlParameter("@OrderId",SqlDbType.VarChar),                                                                                                          
                                            new SqlParameter("@EbayUserId",SqlDbType.VarChar),
                                            new SqlParameter("@RefundId",SqlDbType.VarChar)
                                            };
                        p[0].Value = orderId;
                        p[1].Value = ebayuserId;
                        p[2].Value = refundId;
                        try
                        {
                            DataTable dt = SqlHelper.ExecuteDataTable(SqlHelper.ceterDB_Conn, CommandType.Text, cmdText, p);
                            if (dt.Rows.Count > 0)
                            {
                                retCode = "0";
                                filename = dt.Rows[0][0].ToString();                               
                                if (decimal.Parse(filename)<= 0)
                                {
                                    retCode ="1";
                                    retMsg = "订单余额为："+filename+"，已经无余额可退！.."; 
                                }
                            }
                            else
                            {
                                retCode = "1";
                            }
                        }
                        catch
                        {
                            retCode = "1";
                        }
                    }
                }
                break;
            #endregion
                
            #region 退货单——同步K3
            case "thdtbu"://2012-7-30 修改退货单
                {
                    try
                    {
                        ReturnsOrder returns = new ReturnsOrder();
                        bool val = returns.Add(userId);//退货单同步K3                         
                        if (val)
                        {
                            retCode = "0";
                        }
                        else
                        {
                            retCode = "1";
                            retMsg = "同步失败！..";
                        }
                    }
                    catch
                    {
                        retCode = "1";
                        retMsg = "数据错误！..";
                    }
                }
                break;
            #endregion
            #region 退货单——状态处理
            case "thdchuli"://2012-7-30 修改退货单
                {
                    string ebayuserId = context.Request["ebayid"];
                    string returnId = context.Request["rid"];
                    string rec = context.Request["rec"];
                    string pStatus = context.Request["proStatus"];
                    string remarks = HttpUtility.UrlDecode(context.Request.QueryString["remarks"]);
                    string fid = context.Request["fitemId"];
                    string orderId = "";
                    int proStatus = 0;
                    int fitemId = 0;
                    bool checkParas = true;
                    if (checkParas)
                    {
                        if (!int.TryParse(pStatus, out proStatus))
                        {
                            retCode = "1";
                            retMsg = "处理状态错误!";
                            checkParas = false;
                        }
                    }
                    if (checkParas)
                    {
                        if (!int.TryParse(fid, out fitemId))
                        {
                            retCode = "1";
                            retMsg = "商品编码错误!";
                            checkParas = false;
                        }
                    }
                    ebayuserId = WebUtility.InputText(ebayuserId, 80);
                    returnId = WebUtility.InputText(returnId, 80);
                    rec = WebUtility.InputText(rec, 80);
                    remarks = WebUtility.InputText(remarks, 255);
                    if (checkParas)
                    {                        
                        if (string.IsNullOrEmpty(ebayuserId) && string.IsNullOrEmpty(returnId))
                        {
                            retCode = "1";
                            retMsg = "无退货单可处理";
                        }
                        string cmdText = @"select * from Orders where EbayUserId =@EbayUserId and OrderSalesRecordNumber=@OrderSalesRecordNumber";
                        SqlParameter[] p = {                                                                                                                                                   
                                            new SqlParameter("@EbayUserId",SqlDbType.VarChar),
                                            new SqlParameter("@OrderSalesRecordNumber",SqlDbType.VarChar)
                                            };
                        p[0].Value = ebayuserId;
                        p[1].Value = rec;
                        DataTable dt = SqlHelper.ExecuteDataTable(SqlHelper.ceterDB_Conn, CommandType.Text, cmdText, p);
                        if (dt.Rows.Count == 0)
                        {
                            retCode = "1";
                            retMsg = "Rec_Num和帐号不对应，请重新填写！..";
                            checkParas = false;
                        }
                        else
                        {
                            orderId = dt.Rows[0]["OrderId"].ToString();//获得订单号
                        }                                      
                    }
                    if (checkParas)
                    {                                                
                        ReturnsOrder returns = new ReturnsOrder();
                        try
                        {
                            int val = returns.Match(returnId, ebayuserId, orderId, fitemId, userId, proStatus, remarks);//退货单匹配                           
                            if (val > 0)
                            {
                                retCode = "0";
                            }
                            else
                            {
                                retCode = "1";
                                retMsg = "处理失败！..";
                            }
                        }
                        catch
                        {
                            retCode = "1";
                            retMsg = "数据错误！..";
                        }
                    }
                }
                break;
            #endregion   
            #region 不完全代码批量处理
            case "MoreNoCompleteProcess":
                {
                    string queryDate = Convert.ToDateTime(context.Request["ProDate"]).ToString("yyyyMMdd");
                    string InfoMsg = "";
                    ebay.Dal.Orders o = new Orders();
                    try
                    {
                        o.RadomProcessesNoComplete(queryDate, userId, ref InfoMsg);
                        string path = context.Server.MapPath("~") + "\\UI\\Orders\\bwqOrder.htm";
                        string path1 = context.Server.MapPath("~") + "\\UI\\Orders\\bwqResult.htm";
                        using (StreamReader sr = new StreamReader(path))
                        {
                            string html = sr.ReadToEnd();
                            html = html.Replace("[Content]", InfoMsg);
                            using (StreamWriter sw = new StreamWriter(path1, false, Encoding.UTF8))
                            {
                                sw.Write(html);
                            }
                        }
                        retCode = "0";
                    }
                    catch (Exception ex)
                    {
                        retCode = "1";
                        retMsg = ex.Message.Replace("\r\n", "\\r\\n");
                    }
                }
                break;                
            #endregion
            #region 手动保留
            case "shdbliu":
                {
                    string reason = context.Request["reason"];
                    string data = context.Request["data"];
                    List<OrderInfo> list = GetOrderInfoList(data);
                    bool checkParas = true;
                    if (checkParas)
                    {
                        if (list == null || list.Count == 0)
                        {
                            retCode = "1";
                            retMsg = "空数据!";
                            checkParas = false;
                        }
                    }
                    if (checkParas)
                    {
                        Orders o = new Orders();
                        try
                        {
                            bool val = o.Shdbliu(list, reason, userId);//手动保留
                            if (val)
                            {
                                retCode = "0";
                            }
                            else
                            {
                                retCode = "1";
                            }
                        }
                        catch (Exception ex)
                        {
                            Log.WriteLog(ex.ToString());
                            retCode = "1";
                            retMsg = "服务器内部错误";
                        }
                    }
                }
                break;
            #endregion
            #region
            case "ResetReserve":
                {
                    Orders o = new Orders();
                    try
                    {
                        string msg = "";
                        o.ResetReserve(userId, out msg);
                        retCode = "1";
                        retMsg = msg;
                    }
                    catch (Exception ex)
                    {
                        Log.WriteLog(ex.ToString());
                        retCode = "1";
                        retMsg = "服务器内部错误";
                    }
                
                }
                break;
            #endregion
            #region 手动取消
            case "PPCancelMatch":
                {
                    bool checkParas = true;
                    string pids = context.Request["pids"];
                    pids = WebUtility.InputText(pids, 999);
                    if (checkParas)
                    {
                        if (string.IsNullOrEmpty(pids))
                        {
                            retCode = "1";
                            retMsg = "无订单号可处理";
                            checkParas = false;
                        }
                    }
                    string[] pid = pids.Split(new char[] { ':', ',' });
                    if (checkParas)
                    {
                        Orders o = new Orders();
                        try
                        {
                            o.UpdateMatchFlag(pid);
                            retCode = "0";
                        }
                        catch (Exception ex)
                        {
                            Log.WriteLog(ex.ToString());
                            retCode = "1";
                            retMsg = "服务器内部错误";
                        }
                    }
                }
                break;
            #endregion

            #region 清除标准化标记
            case "updatastandard":
                {
                    string ebayuserId = context.Request["ebId"];
                    string orderId = context.Request["oid"];
                    string orderlineitemid = context.Request["olid"];
                    string type = context.Request["type"];
                    bool checkParas = true;

                    if (checkParas)
                    {
                        if (orderlineitemid == null)
                        {
                            orderlineitemid = "";
                        }
                        ebayuserId = WebUtility.InputText(ebayuserId, 80);
                        orderId = WebUtility.InputText(orderId, 80);
                        orderlineitemid = WebUtility.InputText(orderlineitemid, 30);
                        if (string.IsNullOrEmpty(ebayuserId) && string.IsNullOrEmpty(orderId))
                        {
                            retCode = "1";
                            retMsg = "无订单可处理";
                            checkParas = false;
                        }
                        
                    }
                    if (checkParas)
                    {
                        Orders o = new Orders();
                        DataTable dt = o.CheckStandard(ebayuserId, orderId, orderlineitemid, type);//验证是否可以清楚标准化。
                        if (dt.Rows.Count > 0)
                        {
                            for (int i = 0; i < dt.Rows.Count; i++)
                            {
                                string standard = dt.Rows[i]["Standard"].ToString();
                                string memo = dt.Rows[i]["Memo"].ToString();
                                if (standard != "")
                                {
                                    if (standard != memo && standard != "金额不对" && standard != "在系统中找不到相应的商品信息，请修正商品信息" && standard != "Check Country" && standard != "包含禁用产品" && standard != "地址有问题" && standard != "地址中包含BFPO" && standard != "不完全代码")
                                    {
                                        checkParas = false;
                                        retCode = "1";
                                        retMsg = "标准化为：" + standard + "，不可以清除";
                                        break;
                                    }
                                }
                            }
                        }
                        if (dt == null)
                        {
                            checkParas = false;
                            retCode = "1";
                            retMsg = "服务器内部错误";
                        }
                    }                    
                    if (checkParas)
                    {
                        Orders o = new Orders();
                        try
                        {
                            int val = o.ClearStandard(ebayuserId, orderId, orderlineitemid, userId, type); //清楚标准化标记
                            if (val > 0)
                            {
                                retCode = "0";
                                retMsg = "操作完成";
                            }
                        }
                        catch (Exception ex)
                        {
                            Log.WriteLog(ex.ToString());
                            retCode = "1";
                            retMsg = "服务器内部错误";
                        }
                    }
                }
                break;
            #endregion
            case "AllPreAudit":
                {
                    Orders o = new Orders();
                    try
                    {
                        o.PreAudit(userId);
                        retCode = "0";
                    }
                    catch (Exception ex)
                    {
                        retCode = "1";
                        retMsg = ex.Message;
                    }
                }
                break;
            case "PreAudit":
                {
                    String parseString = context.Request["orders"];
                    List<OrderInfo> infos = GetOrderInfoList(parseString);

                    Orders o = new Orders();
                    retCode = "0";
                    retMsg = String.Empty;
                    
                    foreach (OrderInfo info in infos)
                    {
                        try
                        {
                            o.PreAudit(info.EbayUserId, info.OrderId, userId);
                        }
                        catch (Exception ex)
                        {
                            retCode = "1";
                            retMsg += String.Format("eBayUserId: {0}, OrderId: {1}, {2}\n", info.EbayUserId, info.OrderId, ex.Message);
                        }
                    }
                }
                break;
            case "CancelPreAudit":
                {
                    String parseString = context.Request["orders"];
                    List<OrderInfo> infos = GetOrderInfoList(parseString);

                    Orders o = new Orders();
                    retCode = "0";
                    retMsg = String.Empty;
                    
                    foreach (OrderInfo info in infos)
                    {
                        try
                        {
                            o.CancelPreAudit(info.EbayUserId, info.OrderId, userId);
                        }
                        catch (Exception ex)
                        {
                            retCode = "1";
                            retMsg += String.Format("eBayUserId: {0}, OrderId: {1}, {2}\n", info.EbayUserId, info.OrderId, ex.Message);
                        }
                    }
                }
                break;
            case "Audit":
                {
                    Orders o = new Orders();
                    try
                    {
                        //DataTable dt = o.MoreAuditCheckInventory();//批量审核检查库存
                        //if (dt == null)
                        //{
                        //    retCode = "1";
                        //    retMsg = "系统内部错误";
                        //}
                        //if (dt.Rows.Count > 0)
                        //{
                        //    retCode = "1";
                        //    retMsg = "订单中包含有库存不足的商品，请先做“库存检查”。";
                        //}
                        //else
                        //{
                            int tCount = 0;
                            o.Audit(userId, out tCount);
                            retCode = "0";
                            retMsg = "总发货条数【" + tCount + "】。";
                        //}
                    }
                    catch (Exception ex)
                    {
                        retCode = "1";
                        retMsg = ex.Message;
                    }
                }
                break;
            #region 库存检查
            case "blchul"://保留处理，对未审核订单经行库存检查。
                {
                    Orders o = new Orders();                    
                    try
                    {
                        retCode = o.CheckStock(userId, out retMsg) ? "0" : "1";
                        //DataTable dt = o.MoreAuditCheckInventory();
                        //if (dt == null)
                        //{
                        //    retCode = "1";
                        //    retMsg = "系统内部错误";
                        //}                       
                        //int flag = dt.Rows.Count;
                        //if (dt.Rows.Count > 0)
                        //{                            
                        //    foreach (DataRow r in dt.Rows)
                        //    {                                
                        //        string pid = r["ProductId"].ToString();
                        //        int sqty = int.Parse(r["sQty"].ToString());
                        //        float fqty = float.Parse(r["FQty"].ToString());
                        //        int val = o.BaoLiuCheckInventory(pid, fqty, sqty);//处理库存不足
                        //        if (val > 0)
                        //        {
                        //            flag--;
                        //            continue;
                        //        }
                        //        else
                        //        {
                        //            flag--;
                        //            retMsg = "库存检查有误，详细信息请参阅日志";
                        //            Log.WriteLog("商品编号为" + pid + "订单处理库存检查有误");
                        //            continue;
                        //        }
                        //    }
                        //    if (flag == 0)
                        //    {
                        //        retCode = "0";
                        //    }
                        //}
                        //if (dt.Rows.Count == 0)
                        //{
                        //    retCode = "0";
                        //}
                    }
                    catch (Exception ex)
                    {
                        retCode = "1";
                        retMsg = ex.Message;
                    }
                }
                break;
            #endregion                
            #region 预打印 &打印
            //case "Audit": //审核
            case "PayMent":
                {
                    string BuilderWhere = "";
                    List<SqlParameter> list=new List<SqlParameter>();
                    Orders o = new Orders();
                    //条件审核
                    #region 原审核方法
                    if (cmd == "AuditStop")//停用
                    {
                        BuilderAuditByQueryParas(context, ref BuilderWhere, ref list);  
                        if (k3UserId == -1)
                        {
                            retCode = "1";
                            retMsg = "此用户不属于K3用户,不能操作";
                        }
                        else
                        {
                            retCode = "0";                        
                            DataTable  table = o.GetToK3Order(BuilderWhere, list);
                            if (table == null)
                            {
                                retCode = "1";
                                retMsg = "没有符合审核条件的单据";
                            }                         
                            string Standard = context.Request["Standard"] == null ? "" : context.Request["Standard"].Trim();

                            //筛选掉不能审核的单子
                            if (Standard == "解析正确")
                            {
                                DataTable errtable = table.Select("Standard <> ''","EbayUserId,OrderId").CopyToDataTable();

                                for (int i = 0; i < table.Rows.Count; i++)
                                {
                                    string orderId = table.Rows[i]["OrderId"].ToString();
                                    string ebId = table.Rows[i]["EbayUserId"].ToString();
                                    DataRow[] itemerrRow = errtable.Select("OrderId = '" + orderId + "' and EbayUserId = '" + ebId + "'");
                                    if (itemerrRow.Length > 0)
                                    {
                                        table.Rows.RemoveAt(i);
                                        i--;
                                    }
                                }
                            }
                            string old_OrderId = "";
                            string new_OrderId = "";
                            if (table.Rows.Count > 0)
                            {
                                Orders os = new Orders();
                                StringBuilder result = new StringBuilder();
                                
                                //2012-7-27 统计审核成功的记录数统计：
                                int countNum1 = 0;   //审核成功统计
                                int countNum2 = 0;   //失败统计 
                                int countNum3 = 0;   //未解析
                                int countNum4 = 0;   //商品未进K3
                                int countNum5 = 0;   //未填发货方式
                                DataRow[] rows = table.Select("", "eOrderId asc");
                                foreach (DataRow r in rows)
                                {
                                    new_OrderId = r["eOrderId"].ToString();
                                    if (new_OrderId != old_OrderId)
                                    {
                                        old_OrderId = new_OrderId;
                                        string oorderId = r["OrderId"].ToString();
                                        string ebayUserId = r["EbayUserId"].ToString();

                                        if (table.Select("OrderLineItemId Is Null and eOrderId = '" + new_OrderId + "'").Length > 0)
                                        {
                                            result.AppendLine("<li>订单").Append(oorderId).Append("中还有未解析的CustomLable,不能发货");
                                            countNum3++;
                                        }
                                        else if (table.Select("FitemId <= 0 and eOrderId = '" + new_OrderId + "'").Length > 0)
                                        {
                                            result.AppendLine("<li>订单").Append(oorderId).Append("中还有商品未进K3,不能发货");
                                            countNum4++;
                                        }
                                        else if (table.Select("DeliveryId = 0 and eOrderId = '" + new_OrderId + "'").Length > 0)
                                        {
                                            result.AppendLine("<li>订单").Append(oorderId).Append("中还未选择发货方式,不能发货");
                                            countNum5++;
                                        }
                                        else
                                        {
                                            DateTime saleDate = Convert.ToDateTime(r["SaleDate"]);
                                            DateTime pDate = Convert.ToDateTime(r["CreateDateTime"]);
                                            System.Collections.Generic.List<ebay.Model.CustomerResolveContext> productList = new System.Collections.Generic.List<ebay.Model.CustomerResolveContext>();

                                            DataRow[] pRows = table.Select("eOrderId = '" + new_OrderId + "'");
                                            foreach (DataRow pr in pRows)
                                            {
                                                ebay.Model.CustomerResolveContext m = new ebay.Model.CustomerResolveContext();
                                                if (!string.IsNullOrEmpty(pr["Currency"].ToString()) || !string.IsNullOrEmpty(pr["FitemId"].ToString()) || !string.IsNullOrEmpty(pr["Quantity"].ToString()) || !string.IsNullOrEmpty(pr["SalePrice"].ToString()) || !string.IsNullOrEmpty(pr["WarehouseId"].ToString()))
                                                {
                                                    m.Currency = pr["Currency"].ToString();
                                                    m.FItemId = Convert.ToInt32(pr["FitemId"].ToString());
                                                    m.Quantity = Convert.ToInt32(pr["Quantity"].ToString());
                                                    m.SalePrice = Convert.ToDouble(pr["SalePrice"].ToString()== "" ? "0.00" : pr["SalePrice"].ToString());
                                                    m.FstockId = Convert.ToInt32(pr["WarehouseId"].ToString());
                                                    productList.Add(m);
                                                }
                                            }
                                            try
                                            {
                                                string msg = "";
                                                bool val = os.T_F_Order(k3UserId, ebayUserId, oorderId, userId, 0, 0, saleDate, pDate, productList, out msg);
                                                if (!val)
                                                {
                                                    if (!string.IsNullOrEmpty(msg))
                                                    {
                                                        result.AppendLine("<li>").Append(msg).Append("</li>");
                                                    }
                                                    else
                                                    {
                                                        Log.WriteLog("订单:" + oorderId + "生成发货单失败。\r\n原因：" + msg);
                                                        result.AppendLine("<li>订单").Append(oorderId).Append("生成发货单失败,详情请参阅日志").Append("</li>");
                                                        countNum2++;
                                                    }
                                                }
                                                else
                                                {
                                                    result.AppendLine("<li><span style=\"color:red\">订单").Append(oorderId).Append("生成发货单成功</span></li>");
                                                    countNum1++;
                                                }
                                            }
                                            catch (Exception ex)
                                            {
                                                result.AppendLine("<li><span style=\"color:red\">订单").Append(oorderId).Append("生成发货单失败,详情请参阅日志</span></li>");
                                                Log.WriteLog("订单:" + oorderId + "生成发货单失败。\r\n原因：" + ex.ToString());
                                                countNum2++;
                                                continue;
                                            }
                                        }
                                    }
                                }
                                result.AppendLine("<li><span style=\"color:red\">审核成功总数：").Append(countNum1).Append("条</span></li>");
                                result.AppendLine("<li><span style=\"color:red\">审核失败总数：").Append(countNum2).Append("条</span></li>");
                                result.AppendLine("<li><span style=\"color:red\">未解析总数：").Append(countNum3).Append("条</span></li>");
                                result.AppendLine("<li><span style=\"color:red\">商品未进K3总数：").Append(countNum4).Append("条</span></li>");
                                result.AppendLine("<li><span style=\"color:red\">未填发货方式总数：").Append(countNum5).Append("条</span></li>");
                                string path = context.Server.MapPath("~") + "\\UI\\Orders\\shOrder.htm";
                                string path1 = context.Server.MapPath("~") + "\\UI\\Orders\\Result.htm";
                                using (StreamReader sr = new StreamReader(path))
                                {
                                    string html = sr.ReadToEnd();
                                    html = html.Replace("[Content]", result.ToString());
                                    using (StreamWriter sw = new StreamWriter(path1, false, Encoding.UTF8))
                                    {
                                        sw.Write(html);
                                    }
                                }
                            }
                            else
                            {
                                retCode = "1";
                                retMsg = "没有符合审核条件的单据";
                            }
                        }

                    }
                    #endregion
                    
                    #region 审核修改过
                    if (cmd == "Audit")//2012-10-18
                    {
                        BuilderAuditByQueryParas(context, ref BuilderWhere, ref list);
                        if (k3UserId == -1)
                        {
                            retCode = "1";
                            retMsg = "此用户不属于K3用户,不能操作";
                        }
                        else
                        {
                            retCode = "0";
                            DataTable table = o.GetToK3OrderTest(BuilderWhere, list);                            
                            if (table == null)
                            {
                                retCode = "1";
                                retMsg = "没有符合审核条件的单据";
                            }
                            string Standard = context.Request["Standard"] == null ? "" : context.Request["Standard"].Trim();

                            //筛选掉不能审核的单子
                            if (Standard == "解析正确")
                            {
                                DataTable errtable = table.Select("Standard <> ''", "EbayUserId,OrderId").CopyToDataTable();

                                for (int i = 0; i < table.Rows.Count; i++)
                                {
                                    string orderId = table.Rows[i]["OrderId"].ToString();
                                    string ebId = table.Rows[i]["EbayUserId"].ToString();
                                    DataRow[] itemerrRow = errtable.Select("OrderId = '" + orderId + "' and EbayUserId = '" + ebId + "'");
                                    if (itemerrRow.Length > 0)
                                    {
                                        table.Rows.RemoveAt(i);
                                        i--;
                                    }
                                }
                            }
                            string old_OrderId = "";
                            string new_OrderId = "";
                            if (table.Rows.Count > 0)
                            {
                                Orders os = new Orders();
                                StringBuilder result = new StringBuilder();

                                //2012-7-27 统计审核成功的记录数统计：                                
                                int countNum1 = 0;   //审核成功统计
                                int countNum2 = 0;   //失败统计 
                                int countNum3 = 0;   //未解析
                                int countNum4 = 0;   //商品未进K3
                                int countNum5 = 0;   //未填发货方式
                                string flag = "0";//是否进行审核操作
                                DataRow[] rows = table.Select("", "eOrderId asc");
                                foreach (DataRow r in rows)
                                {
                                    new_OrderId = r["eOrderId"].ToString();
                                    if (new_OrderId != old_OrderId)
                                    {
                                        old_OrderId = new_OrderId;
                                        string oorderId = r["OrderId"].ToString();
                                        string ebayUserId = r["EbayUserId"].ToString();
                                        decimal gross = decimal.Parse(r["Gross"].ToString());
                                        if (table.Select("OrderLineItemId Is Null and eOrderId = '" + new_OrderId + "'").Length > 0)
                                        {
                                            result.AppendLine("<li>订单").Append(oorderId).Append("中还有未解析的CustomLable,不能发货");
                                            countNum3++;
                                        }
                                        else if (table.Select("FitemId <= 0 and eOrderId = '" + new_OrderId + "'").Length > 0)
                                        {
                                            result.AppendLine("<li>订单").Append(oorderId).Append("中还有商品未进K3,不能发货");
                                            countNum4++;
                                        }
                                        else if (table.Select("DeliveryId = 0 and eOrderId = '" + new_OrderId + "'").Length > 0)
                                        {
                                            result.AppendLine("<li>订单").Append(oorderId).Append("中还未选择发货方式,不能发货");
                                            countNum5++;
                                        }                                                                                   
                                        else
                                        {                                                                                       
                                            DateTime saleDate = Convert.ToDateTime(r["SaleDate"]);
                                            DateTime pDate = Convert.ToDateTime(r["CreateDateTime"]);
                                            System.Collections.Generic.List<ebay.Model.CustomerResolveContext> productList = new System.Collections.Generic.List<ebay.Model.CustomerResolveContext>();
                                            DataRow[] pRows = table.Select("eOrderId = '" + new_OrderId + "'");    
                                                                             
                                            foreach (DataRow pr in pRows)
                                            {
                                                ebay.Model.CustomerResolveContext m = new ebay.Model.CustomerResolveContext();
                                                if (!string.IsNullOrEmpty(pr["Currency"].ToString()) || !string.IsNullOrEmpty(pr["FitemId"].ToString()) || !string.IsNullOrEmpty(pr["Quantity"].ToString()) || !string.IsNullOrEmpty(pr["SalePrice"].ToString()) || !string.IsNullOrEmpty(pr["WarehouseId"].ToString()))
                                                {
                                                    m.Currency = pr["Currency"].ToString();
                                                    m.FItemId = Convert.ToInt32(pr["FitemId"].ToString());
                                                    m.Quantity = Convert.ToInt32(pr["Quantity"].ToString());
                                                    m.SalePrice = Convert.ToDouble(pr["SalePrice"].ToString() == "" ? "0.00" : pr["SalePrice"].ToString());
                                                    m.FstockId = Convert.ToInt32(pr["WarehouseId"].ToString());
                                                    //检查库存                                                    
                                                    int val2=os.CheckInventory(m.FItemId, m.FstockId,m.Quantity,ebayUserId, oorderId); //检查库存
                                                    if (val2 == 0)
                                                    {
                                                        result.AppendLine("<li>订单:").Append(oorderId).Append("已缺货保留").Append("</li>");
                                                        flag = "1";
                                                        break;
                                                    }
                                                    else
                                                    {
                                                        productList.Add(m);
                                                    }
                                                }
                                            }
                                            try
                                            {
                                                if (flag != "1")
                                                {
                                                    string msg = "";
                                                    bool val = os.T_F_OrderTest(k3UserId, ebayUserId, oorderId, gross, userId, 0, 0, saleDate, pDate, productList, out msg);
                                                    if (!val)
                                                    {
                                                        if (!string.IsNullOrEmpty(msg))
                                                        {
                                                            result.AppendLine("<li>").Append(msg).Append("</li>");
                                                        }
                                                        else
                                                        {
                                                            Log.WriteLog("订单:" + oorderId + "生成发货单失败。\r\n原因：" + msg);
                                                            result.AppendLine("<li>订单").Append(oorderId).Append("生成发货单失败,详情请参阅日志").Append("</li>");
                                                            countNum2++;
                                                        }
                                                    }
                                                    else
                                                    {
                                                        result.AppendLine("<li><span style=\"color:red\">订单").Append(oorderId).Append("生成发货单成功</span></li>");
                                                        countNum1++;
                                                    }
                                                }
                                            }
                                            catch (Exception ex)
                                            {
                                                result.AppendLine("<li><span style=\"color:red\">订单").Append(oorderId).Append("生成发货单失败,详情请参阅日志</span></li>");
                                                Log.WriteLog("订单:" + oorderId + "生成发货单失败。\r\n原因：" + ex.ToString());
                                                countNum2++;
                                                continue;
                                            }
                                        }
                                    }
                                }
                                result.AppendLine("<li><span style=\"color:red\">审核成功总数：").Append(countNum1).Append("条</span></li>");
                                result.AppendLine("<li><span style=\"color:red\">审核失败总数：").Append(countNum2).Append("条</span></li>");
                                result.AppendLine("<li><span style=\"color:red\">未解析总数：").Append(countNum3).Append("条</span></li>");
                                result.AppendLine("<li><span style=\"color:red\">商品未进K3总数：").Append(countNum4).Append("条</span></li>");
                                result.AppendLine("<li><span style=\"color:red\">未填发货方式总数：").Append(countNum5).Append("条</span></li>");
                                string path = context.Server.MapPath("~") + "\\UI\\Orders\\shOrder.htm";
                                string path1 = context.Server.MapPath("~") + "\\UI\\Orders\\Result.htm";
                                using (StreamReader sr = new StreamReader(path))
                                {
                                    string html = sr.ReadToEnd();
                                    html = html.Replace("[Content]", result.ToString());
                                    using (StreamWriter sw = new StreamWriter(path1, false, Encoding.UTF8))
                                    {
                                        sw.Write(html);
                                    }
                                }
                            }
                            else
                            {
                                retCode = "1";
                                retMsg = "没有符合审核条件的单据";
                            }
                        }

                    }   
                    #endregion
                    //确认收款
                    else if (cmd == "PayMent")
                    {
                        BuilderByQueryParas(context, ref BuilderWhere, ref list);  
                        bool val = o.ConfirmPay(BuilderWhere, userId, list);
                        if (val)
                        {
                            retCode = "0";
                        }
                        else {
                            retCode = "1";
                            retMsg = "操作出现错误,详情请参与错误日志";
                        }
                    }
                    else
                    {
                        retCode = "1";
                        retMsg = "错误的指令";

                    }
                }
                break;
            #endregion

        }
        context.Response.Write("[{\"retCode\":\"" + retCode + "\",\"retMsg\":\"" + retMsg + "\",\"fn\":\"" + filename + "\",\"ProductId\":\"" + productId + "\"}]");

    }

    void BuilderByQueryParas(HttpContext context,ref string BuilderWhere, ref List<SqlParameter> list)
    {
        string etype = context.Request["etype"];
        if (etype == "1")
        {
            BuilderWhere += " And Convert(Varchar(8),Orders.Mtime,112) = @Today";
            SqlParameter p = new SqlParameter("@Today", SqlDbType.VarChar);
            p.Value = DateTime.Now.ToString("yyyyMMdd");
            list.Add(p);
        }
        else if (etype == "2")
        {
            GetQueryPatas(context, ref BuilderWhere, ref list);
        }
        else if (etype == "3")
        {
            GetOrderList(context, ref BuilderWhere, ref list);
        }
    }


    void BuilderAuditByQueryParas(HttpContext context, ref string BuilderWhere, ref List<SqlParameter> list)
    {
        string etype = context.Request["etype"];
        if (etype == "1")
        {
            BuilderWhere += " And Convert(Varchar(8),Orders.Mtime,112) = @Today";
            SqlParameter p = new SqlParameter("@Today", SqlDbType.VarChar);
            p.Value = DateTime.Now.ToString("yyyyMMdd");
            list.Add(p);
        }
        else if (etype == "2")
        {
            GetAuditQueryPatas(context, ref BuilderWhere, ref list);
        }
        else if (etype == "3")
        {
            GetOrderList(context, ref BuilderWhere, ref list);
        }
    }
    void GetQueryPatas(HttpContext context, ref string BuilderWhere, ref List<SqlParameter> list)
    {
        string ebayUserId = context.Request["ebayUserId"];
        string timeFrom = context.Request["timeFrom"];
        string timeTo = context.Request["timeTo"];
        string orderId = context.Request["orderId"];
        string buyerId = context.Request["BuyerId"];
        string buyerName = context.Request["BuyerName"];
        string NewOrderId = context.Request["NewOrderId"];
        string OrderStatusId = context.Request["OrderStatusId"];
        string Standard = context.Request["Standard"] == null ? "" : context.Request["Standard"].Trim();
        string rtype = context.Request["rtype"];
        if (!string.IsNullOrEmpty(orderId))
        {
            BuilderWhere += " And Orders.OrderSalesRecordNumber = @OrderSalesRecordNumber";
            SqlParameter p = new SqlParameter("@OrderSalesRecordNumber", SqlDbType.VarChar);
            p.Value = orderId;
            list.Add(p);
        }
        if (!string.IsNullOrEmpty(ebayUserId.Trim()))
        {
            BuilderWhere += " And Orders.EbayUserId = @ebayUserId";
            SqlParameter p = new SqlParameter("@ebayUserId", SqlDbType.VarChar);
            p.Value = ebayUserId;
            list.Add(p);
        }

        if (!string.IsNullOrEmpty(buyerId))
        {
            BuilderWhere += " And Orders.UserID = @buyerId";
            SqlParameter p = new SqlParameter("@buyerId", SqlDbType.VarChar);
            p.Value = buyerId;
            list.Add(p);
        }

        if (!string.IsNullOrEmpty(buyerName))
        {
            BuilderWhere += " And Orders.BuyerName = @buyerName";
            SqlParameter p = new SqlParameter("@buyerName", SqlDbType.VarChar);
            p.Value = buyerName;
            list.Add(p);
        }

        string bdate = "";

        if (rtype == "1")
        {
            bdate = " And CONVERT(varchar(19),Orders.MatchDate,21) >= @beginDate And CONVERT(varchar(19),Orders.MatchDate,21) <= @endDate ";
            SqlParameter p = new SqlParameter("@beginDate", SqlDbType.VarChar);
            p.Value = timeFrom;
            list.Add(p);
            SqlParameter p2 = new SqlParameter("@endDate", SqlDbType.VarChar);
            p2.Value = timeTo;
            list.Add(p2);
        }
        else if (rtype == "2")
        {
            bdate = " And  CONVERT(varchar(19),Orders.SaleDate,21) >= @beginDate And CONVERT(varchar(19),Orders.SaleDate,21) <= @endDate ";
            SqlParameter p = new SqlParameter("@beginDate", SqlDbType.VarChar);
            p.Value = timeFrom;
            list.Add(p);
            SqlParameter p2 = new SqlParameter("@endDate", SqlDbType.VarChar);
            p2.Value = timeTo;
            list.Add(p2);
        }
        else if (rtype == "3")
        {
            bdate = " And CONVERT(varchar(19),Orders.Mtime,21) >= @beginDate And CONVERT(varchar(19),Orders.Mtime,21) <= @endDate ";
            SqlParameter p = new SqlParameter("@beginDate", SqlDbType.VarChar);
            p.Value = timeFrom;
            list.Add(p);
            SqlParameter p2 = new SqlParameter("@endDate", SqlDbType.VarChar);
            p2.Value = timeTo;
            list.Add(p2);
        }
        if (Standard != "Select")
        {
            if (Standard.Trim() == "解析正确")
            {
                BuilderWhere += @" and not exists (select 1 from Orders o where Orders.EbayUserId = o.EbayUserId and Orders.OrderId = o.OrderId and o.Standard <> '')";
            }
            else if (Standard == "金额不对")
            {
                BuilderWhere += " and Orders.Standard = '金额不对'";
            }
            else if (Standard == "在系统中找不到相应的商品信息，请修正商品信息")
            {
                BuilderWhere += " and Orders.Standard = '在系统中找不到相应的商品信息，请修正商品信息'";
            }
            else if (Standard == "不完全代码")
            {
                BuilderWhere += " Orders.Standard = '不完全代码'";
            }
            else if (Standard == "发货方式为空")
            {
                BuilderWhere += " Orders.OrderRetentionReson = '发货方式为空'";
            }
            else if (Standard == "留言")
            {
                BuilderWhere += " Orders.Standard=Memo and Memo <> ''";
            }

        }
        BuilderWhere += bdate;
    }

    void GetAuditQueryPatas(HttpContext context, ref string BuilderWhere, ref List<SqlParameter> list)
    {
        string ebayUserId = context.Request["ebayUserId"];
        string timeFrom = context.Request["timeFrom"];
        string timeTo = context.Request["timeTo"];
        string orderId = context.Request["orderId"];
        string buyerId = context.Request["BuyerId"];
        string buyerName = context.Request["BuyerName"];
        string NewOrderId = context.Request["NewOrderId"];
        string OrderStatusId = context.Request["OrderStatusId"];
        string Standard = context.Request["Standard"] == null ? "" : context.Request["Standard"].Trim();
        string rtype = context.Request["rtype"];
        if (!string.IsNullOrEmpty(orderId))
        {
            BuilderWhere += " And Orders.OrderSalesRecordNumber = @OrderSalesRecordNumber";
            SqlParameter p = new SqlParameter("@OrderSalesRecordNumber", SqlDbType.VarChar);
            p.Value = orderId;
            list.Add(p);
        }
        if (!string.IsNullOrEmpty(ebayUserId.Trim()))
        {
            BuilderWhere += " And Orders.EbayUserId = @ebayUserId";
            SqlParameter p = new SqlParameter("@ebayUserId", SqlDbType.VarChar);
            p.Value = ebayUserId;
            list.Add(p);
        }

        if (!string.IsNullOrEmpty(buyerId))
        {
            BuilderWhere += " And Orders.UserID = @buyerId";
            SqlParameter p = new SqlParameter("@buyerId", SqlDbType.VarChar);
            p.Value = buyerId;
            list.Add(p);
        }

        if (!string.IsNullOrEmpty(buyerName))
        {
            BuilderWhere += " And Orders.BuyerName = @buyerName";
            SqlParameter p = new SqlParameter("@buyerName", SqlDbType.VarChar);
            p.Value = buyerName;
            list.Add(p);
        }

        string bdate = "";

        if (rtype == "1")
        {
            bdate = " And CONVERT(varchar(19),Orders.MatchDate,21) >= @beginDate And CONVERT(varchar(19),Orders.MatchDate,21) <= @endDate ";
            SqlParameter p = new SqlParameter("@beginDate", SqlDbType.VarChar);
            p.Value = timeFrom;
            list.Add(p);
            SqlParameter p2 = new SqlParameter("@endDate", SqlDbType.VarChar);
            p2.Value = timeTo;
            list.Add(p2);
        }
        else if (rtype == "2")
        {
            bdate = " And  CONVERT(varchar(19),Orders.SaleDate,21) >= @beginDate And CONVERT(varchar(19),Orders.SaleDate,21) <= @endDate ";
            SqlParameter p = new SqlParameter("@beginDate", SqlDbType.VarChar);
            p.Value = timeFrom;
            list.Add(p);
            SqlParameter p2 = new SqlParameter("@endDate", SqlDbType.VarChar);
            p2.Value = timeTo;
            list.Add(p2);
        }
        else if (rtype == "3")
        {
            bdate = " And CONVERT(varchar(19),Orders.Mtime,21) >= @beginDate And CONVERT(varchar(19),Orders.Mtime,21) <= @endDate ";
            SqlParameter p = new SqlParameter("@beginDate", SqlDbType.VarChar);
            p.Value = timeFrom;
            list.Add(p);
            SqlParameter p2 = new SqlParameter("@endDate", SqlDbType.VarChar);
            p2.Value = timeTo;
            list.Add(p2);
        } 
        if (Standard != "Select")
        {
            if (Standard == "金额不对")
            {
                BuilderWhere += " and Orders.Standard = '金额不对'";
            }
            else if (Standard == "在系统中找不到相应的商品信息，请修正商品信息")
            {
                BuilderWhere += " and Orders.Standard = '在系统中找不到相应的商品信息，请修正商品信息'";
            }
            else if (Standard == "不完全代码")
            {
                BuilderWhere += " Orders.Standard = '不完全代码'";
            }
            else if (Standard == "发货方式为空")
            {
                BuilderWhere += " Orders.OrderRetentionReson = '发货方式为空'";
            }
            else if (Standard == "留言")
            {
                BuilderWhere += " Orders.Standard=Memo and Memo <> ''";
            }

        }
        BuilderWhere += bdate;
    }
    List<OrderInfo> GetOrderInfoList(string data)
    {
        if (string.IsNullOrEmpty(data))
        {
            return null;
        }
        DataTable dt = JsonConvert.DeserializeObject(data, typeof(DataTable)) as DataTable;
        return JsonConvert.DeserializeObject(data, typeof(List<OrderInfo>)) as List<OrderInfo>;    
    }
    void GetOrderList(HttpContext context, ref string BuilderWhere, ref List<SqlParameter> list)
    {
        string data = context.Request["data"];
        List<OrderInfo> orderlist = GetOrderInfoList(data);
        if (orderlist != null)
        {
            if (orderlist.Count > 0)
            {
                //修改时间：2012-8-10
                BuilderWhere += " And ((Orders.EbayUserId >= @EbayUserId0 And Orders.OrderId = @OrderId0)";
               // BuilderWhere += " And ((Orders.EbayUserId >= @EbayUserId0 And Orders.OrderSalesRecordNumber = @OrderId0)";
                SqlParameter p = new SqlParameter("@EbayUserId0", SqlDbType.VarChar);
                p.Value = orderlist[0].EbayUserId;
                list.Add(p);

                SqlParameter p2 = new SqlParameter("@OrderId0", SqlDbType.VarChar);
                p2.Value = orderlist[0].OrderId;
                list.Add(p2);
                
                for (int i = 1; i < orderlist.Count; i++)
                {
                    //修改时间：2012-8-10
                    BuilderWhere += " Or (Orders.EbayUserId >= @EbayUserId" + i + " And Orders.OrderId = @OrderId" + i + ")";
                   // BuilderWhere += " Or (Orders.EbayUserId >= @EbayUserId" + i + " And Orders.OrderSalesRecordNumber = @OrderId" + i + ")";
                    p = new SqlParameter("@EbayUserId" + i, SqlDbType.VarChar);
                    p.Value = orderlist[i].EbayUserId;
                    list.Add(p);
                    p2 = new SqlParameter("@OrderId" + i, SqlDbType.VarChar);
                    p2.Value = orderlist[i].OrderId;
                    list.Add(p2);
                }
                BuilderWhere += ")";
            }
        }
    
    }
    public bool IsReusable {
        get {
            return false;
        }
    }

    /// <summary>
    /// parcelprint中是否已有目标订单
    /// </summary>
    /// <param name="orderId">订单号</param>
    /// <returns></returns>
    int PrintRow(string orderId)
    {
        string cmdText = @"SELECT [OrderId],[printed]      
                                FROM [CenterDB].[dbo].[ParcelPrint]
                                where [OrderId]=@OrderId
                             ";
        SqlParameter[] p = {                                           
                                           new SqlParameter("@OrderId",SqlDbType.VarChar)
                                           };
       
        p[0].Value = orderId;
        DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.ceterDB_Conn, CommandType.Text, cmdText, p);
        int rows = ds.Tables[0].Rows.Count;
        return rows;        
    }

}